user7351292
user7351292

Reputation:

django-forms not rendering errors

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

Here's my code:

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>

Upvotes: 0

Views: 611

Answers (1)

Bug is on this line

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

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

Add your return statement inside your POST block also

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

or

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

Upvotes: 2

Related Questions