【问题标题】:django-forms not rendering errorsdjango-forms 不呈现错误
【发布时间】:2016-12-29 16:42:00
【问题描述】:

我在表单中呈现错误时遇到问题,当表单无效时,它只是重新加载页面并且错误不显示。 我想显示错误,例如显示电子邮件无效或电话号码包含无效字符的文本

这是我的代码:

views.py

def contact(request):
    form_class = ContactForm

    if request.method == 'POST':
        form = form_class(data=request.POST)

        if form.is_valid():
            contact_name = request.POST.get(
                'contact_name'
                , '')
            contact_email = request.POST.get(
                'contact_email'
                , '')
            contact_phone = request.POST.get(
                'contact_phone'
                , '')
            form_content = request.POST.get(
                'content'
                , '')

            # Email the profile with the
            # contact information
            template = get_template('contact_form.txt')
            context = Context({
                'contact_name': contact_name,
                'contact_email': contact_email,
                'contact_phone': contact_phone,
                'form_content': form_content,
            })
            content = template.render(context)

            email = EmailMessage(
                "Novo contato pelo site",
                 content,
                "email@gmail.com",
                ['myemail@hotmail.com'],
                headers={'Reply-To': contact_email}
            )
            email.send()

            print(form.cleaned_data)
        else:
            print(form)

    return render(request, 'info/contact_us.html', {
        'form': form_class,
    })

forms.py

class ContactForm(forms.Form):
    contact_name = forms.CharField(max_length=150,
                                  label="Nome",
                                  required=True,)
    contact_email = forms.EmailField(max_length=150,
                                     label="Email",
                                     required=True,)
    contact_phone = forms.RegexField(max_length=12,
                                    label="Fone",
                                    required=False,
                                    regex=r'[0-9]+',)
    content = forms.CharField(max_length=10000,
                              required=True,
                              widget=forms.Textarea,)

    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_id = 'id-form'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_action = ''

        self.helper.add_input(Submit('submit', 'Submit'))

        self.fields['contact_name'].label = "Name:"
        self.fields['contact_email'].label = "Email:"
        self.fields['contact_phone'].label = "Phone:"
        self.fields['content'].label = "Message:"

    def clean(self):
        cleaned_data = super(ContactForm, self).clean()
        contact_name = cleaned_data.get("contact_name")
        contact_email = cleaned_data.get("contact_email")
        contact_phone = cleaned_data.get("contact_phone")
        content = cleaned_data.get("content")

        if 'asd' not in contact_email:
            raise forms.ValidationError("Invalid Email")

contact_us.html

<div id="form" class="col-sm-6">
     {% crispy form form.helper %}
</div>

【问题讨论】:

  • 该视图的其余部分在哪里?目前,您会收到该代码的服务器错误。
  • 糟糕,刚刚添加了我忘记的最后一部分。

标签: python django django-forms


【解决方案1】:

错误就在这一行

return render(request, 'info/contact_us.html', {
    'form': form_class,
})

当调用 GET 方法时,它会加载空表单,即 form=form_class(),在 POST 方法上,它应该是 form=form_class(request.POST)。根据上面的代码,它再次加载新的表单

在你的 POST 块中添加你的 return 语句

return render(request, 'info/contact_us.html', {
    'form': form_class(request.POST),
})

return render(request, 'info/contact_us.html', {
    'form': form,
})

【讨论】:

  • form_class(request.POST) 有效,但在表单上写任何内容之前会显示错误
  • 刚刚解决了这个问题,我必须在 'if_valid()' 的末尾添加一个 'return render form_class(request.POST)' 并在代码末尾使用 'return render form_class'
猜你喜欢
  • 1970-01-01
  • 2013-10-06
  • 2015-06-06
  • 2020-03-13
  • 2015-06-17
  • 1970-01-01
  • 2016-03-09
  • 1970-01-01
  • 2018-07-12
相关资源
最近更新 更多