在Django模板中显示基于字段的错误

时间:2019-05-24 20:39:57

标签: django forms validation django-templates

我正在使用以下页面上的代码:

https://docs.djangoproject.com/en/2.2/ref/forms/validation/

尤其是以下内容:

from django import forms

class ContactForm(forms.Form):
   subject = forms.CharField(max_length=100)
   message = forms.CharField()
   sender = forms.EmailField()
   recipients = MultiEmailField()
   cc_myself = forms.BooleanField(required=False)

   def clean(self):
       cleaned_data = super().clean()
       cc_myself = cleaned_data.get("cc_myself")
       subject = cleaned_data.get("subject")

       if cc_myself and subject and "help" not in subject:
           msg = "Must put 'help' in subject when cc'ing yourself."
           self.add_error('cc_myself', msg)
           self.add_error('subject', msg)

但是我无法使用以下字段访问模板中的错误:

 <form action="contact" method="post" id="contact-form">
    {% csrf_token %}
    {{ form.cc_myself.errors }}
    {{ form.cc_myself }}
 </form>

有人遇到过这个问题吗?

0 个答案:

没有答案