如何使用CreateView Django在模板中显示验证错误
我正在使用扩展的用户模型和一个通用的CreateView。
class SignUp(CreateView):
form_class = forms.SignUpForm
success_url = '/accounts/login/'
template_name = 'accounts/signup.html'
如何访问模板中的表单验证错误?它们必须在那里,因为当我做{{form.as_p}}时,出现错误。我尝试了{{form.errors}}和{{field.errors}}},但是其中没有什么。我可以在模板中调用一个简单的标签以显示错误吗?谢谢。
I am using an extended User model and a generic CreateView.
class SignUp(CreateView):
form_class = forms.SignUpForm
success_url = '/accounts/login/'
template_name = 'accounts/signup.html'
How do I access the form validation errors in my template? They must be there because when I do {{ form.as_p }} the errors show up. I have tried {{ form.errors }} and {{ field.errors }} but there is nothing in them. Is there a simple tag I can call in my template to show the errors? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果愿意,您可以手动执行。每个字段都可以使用{form.name_of_field}}作为表单的属性可用,在Django模板中,将适当地渲染。例如:
如果您想在顶页上循环一次所有错误。
如果您在每个表单字段中都使用相同的html,则可以通过依次使用{%for%}循环循环浏览每个字段来减少重复代码:
您可以检查许多方法在下面的django文档中执行此操作。 URL
https://docs.djangoproject .com/en/4.0/topics/forms/#looping-over-the-form-s-fields
you can do it manually if you like. Each field is available as an attribute of the form using {{ form.name_of_field }}, and in a Django template, will be rendered appropriately. For example:
and if you want to loop all errors once on the top page.
If you’re using the same HTML for each of your form fields, you can reduce duplicate code by looping through each field in turn using a {% for %} loop:
you can check many methods to do that in Django documentation in the below URL
https://docs.djangoproject.com/en/4.0/topics/forms/#looping-over-the-form-s-fields