python - Django 表单问题?
问题描述
关于Django表单问题先给出models.py和forms.py
图片描述

再给出views.py的代码
def articleUpdate(request, articleId):’’’Update the article instance: 1. Get the article to update; redirect to 404 if not found2. Render a bound form if the method is GET3. If the form is valid, save it to the model, otherwise render abound form with error messages’’’articleToUpdate = get_object_or_404( Article, id=articleId)template = ’article/articleCreateUpdate.html’if request.method == ’GET’: print(ArticleForm(instance=articleToUpdate)) articleForm = ArticleForm(instance=articleToUpdate) return render(request, template, {’articleForm’:articleForm, ’article’:articleToUpdate})# POSTarticleForm = ArticleForm(request.POST, instance=articleToUpdate)if not articleForm.is_valid(): return render(request, template, {’articleForm’:articleForm, ’article’:articleToUpdate})articleForm.save()messages.success(request, ’文章已修改’)return redirect(’article:articleRead’, articleId=articleId)def commentCreate(request, articleId): ’’’Create a new article instance1. If method is GET, render an empty form2 . If method is POST, perform form validation. Display error messages if the form is invalid3. Save the form to the model and redirect to the article page’’’template = ’article/commentCreate.html’ articleToUpdate = get_object_or_404( Article, id=articleId) if request.method == ’GET’:return render(request, template,{’commentForm’:CommentForm(), ’article’:articleToUpdate}) # POSTcommentForm = CommentForm(request.POST, instance=articleToUpdate) if not commentForm.is_valid():return render(request, template, {’commentForm’:commentForm(), ’article’:articleToUpdate}) commentForm.save() messages.success(request,’留言已新增’) return redirect(’article:articleRead’,articleId=articleId)
两则方法是几乎是一样的,都是用forms表单,但是我使用的forms表单并不是同一类,一个是ArticleForm一个是CommentForm但是结果出现在views:commentCreate里它的效果是等于articleUpdate,即新增留言变成修改文章内容

问题解答
回答1:表单是类,你取出数据,为什么不填充到表单中。
else:form = CommentsForm(request.POST)if form.is_valid():
相关文章:
1. PHP搜索功能的实现 哪里错了2. 新建index文件夹,然后把controller 以及文件index.php放入index文件夹。修改htaccess文件为扩展访问。但是访问的时候提示页面错误!请稍后再试。PHP版本正常,请老师解答3. php - SQL 一条语句查询出文章和对应的文章标签4. angular.js使用$resource服务把数据存入mongodb的问题。5. 下载32位vc9和11、14运行库时解压错误6. 请问一下,图片上传成功,但是后台对应文件夹里面却没有图片,这是什么原因?(已部署到服务器)7. mysql优化 - mysql like语句会导致全表扫描?8. java - mysql缓存问题9. mysql - 千万级数据表如何有效的变更字段?10. java - 触发器使两张表同时更新

网公网安备