Django的形式不呈现错误

Django的形式不呈现错误

本文介绍了Django的形式不呈现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having issues rendering errors in my form, when the form is invalid, it just reloads the page and the errors don't show.I want to show the errors, like showing a text saying that the email is invalid, or that the phone number contain invalid characters

这是我的代码:

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 protected]",
                ['[email protected]'],
                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>


推荐答案

错误在此行

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

调用GET方法时,它将在POST方法上加载为form = form_class()的Empty表单。是form = form_class(request.POST)。按照上面的代码,它将再次加载新的表单

When GET method is called it loads the Empty form that is form=form_class(), on POST method it should be form=form_class(request.POST). As per the above code, it is again loading fresh form

也在POST块中添加return语句

Add your return statement inside your POST block also

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

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

这篇关于Django的形式不呈现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 10:23