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. python如何不改动文件的情况下修改文件的 修改日期2. node.js - node_moduls太多了3. angular.js - 不适用其他构建工具,怎么搭建angular1项目4. python - django 里自定义的 login 方法,如何使用 login_required()5. css3 - [CSS] 动画效果 3D翻转bug6. mysql优化 - mysql count(id)查询速度如何优化?7. angular.js - Angular路由和express路由的组合使用问题8. mysql主从 - 请教下mysql 主动-被动模式的双主配置 和 主从配置在应用上有什么区别?9. 主从备份 - 跪求mysql 高可用主从方案10. java8中,逻辑与 & 符号用在接口类上代表什么意思
![css3 - [CSS] 动画效果 3D翻转bug](http://www.haobala.com/attached/image/news/202304/110831f073.png)