一个模板 - 多个模型错误
views.py
def fadded(request): if request.method == "POST": fform = FtForm(request.POST) bform = BgForm(request.POST) if fform.is_valid() and bform.is_valid(): bcontent=bform.save() fcontent=fform.save() else: return render_to_response("ft.html", { "fform": fform, "bform": bform, },context_instance=RequestContext(request)) return HttpResponse('OK!')
ft.html
... {% if form.errors%}{% for error in form.errors %} {{ error|escape }} {% endfor %}
{% endif %} ...
有两种模型形式:fform 和 bform。它们代表两个不同的模型,但在同一模板中使用。我正在尝试保存两者并从两者中获取表单/字段错误。但如果已经存在 fform.errors,django 不会显示 bform.errors(并且可能甚至不会创建 bform)。有什么不同的建议吗?
views.py
def fadded(request): if request.method == "POST": fform = FtForm(request.POST) bform = BgForm(request.POST) if fform.is_valid() and bform.is_valid(): bcontent=bform.save() fcontent=fform.save() else: return render_to_response("ft.html", { "fform": fform, "bform": bform, },context_instance=RequestContext(request)) return HttpResponse('OK!')
ft.html
... {% if form.errors%}{% for error in form.errors %} {{ error|escape }} {% endfor %}
{% endif %} ...
There are two modelforms: fform and bform. They represent two different models, but are used in same template. I'm trying to save both and to get form-/fielderrors from both. But if there are already fform.errors, django doesn't shows bform.errors(and propably doesn't even create bform). Any proposals for a different way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您的设置,两个表单都会传递数据并准备好进行验证。应该没有问题。
在您的模板中,您必须显示两种表单错误(我只看到模板中检查了一种表单)
Given your setup, both forms are passed data and are ready to be validated. There shouldn't be a problem.
In your template, you'd have to display both forms errors (I only see one form being checked in your template)
您需要使用基于类的视图!
以下是在一个 Django 视图中使用多个表单的快速示例。
从 django.contrib 导入消息
从 django.views.generic 导入 TemplateView
从 .forms 导入 AddPostForm、AddCommentForm
from .models import Comment
在这个例子中,我在网上找到了(在 RIP教程),我们使用模板视图。基于类的视图是解决这个问题的方法。以下是有关如何在 Django 上使用基于类的视图的最新文档的链接。享受阅读的乐趣,最重要的是要有耐心。 https://docs.djangoproject.com/en/2.2/topics /class-based-views/
希望这可以帮助引导您走向正确的方向。期待听到事情进展如何。
You need to use Class based views!
Here is a quick example of using multiple forms in one Django view.
from django.contrib import messages
from django.views.generic import TemplateView
from .forms import AddPostForm, AddCommentForm
from .models import Comment
In this example I have found online (on RIP tutorial), we use TEMPLATE VIEW. Class-based views are your way around this. Here is a link to the most up-to-date documentation on how to use class-based views on Django. Have fun reading, and most of all, patience. https://docs.djangoproject.com/en/2.2/topics/class-based-views/
Hopefully, this could help to guide you in the right direction. Looking forward to hearing from how it goes.