Cathal
Cathal

Reputation: 328

Django form not storing values on validation fail

I can't get Django to retain entered form values when validation fails. I have created a test page and used the code in the Django guide, and it still doesn't work.

From the Django guide:

We call the form’s is_valid() method; if it’s not True, we go back to the template with the form. This time the form is no longer empty (unbound) so the HTML form will be populated with the data previously submitted, where it can be edited and corrected as required.

And here is my code:

#views.py

def test(request):
    if request.method == 'POST':
        form = NewAwardForm(request.POST)

        if form.is_valid():
            return redirect('/test/')

    else:
        form = NewAwardForm()

    print(form)
    return render(request, 'test.html', {'form': form})

test.html

<form action="/test/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

forms.py

class NewAwardForm(forms.Form):
    recipient_email = forms.EmailField(label='Recipient Email', max_length=100)

Can anyone spot my mistake?

Upvotes: 0

Views: 1554

Answers (1)

Alasdair
Alasdair

Reputation: 308799

Django renders the email field with type="email". The HTML validation will prevent the browser from submitting an invalid email to the server.

You could test the view by adding a clean method to the form that rejects any emails ending in "example.com".

class NewAwardForm(forms.Form):
    recipient_email = forms.EmailField(label='Recipient Email', max_length=100)

    def clean_recipient_email(self):
        if self.cleaned_data['recipient_email'].endswith('example.com'):
            raise forms.ValidationError("No example.org emails allowed")

Now, if you enter [email protected] and submit the form the HTML validation will allow the request to be submitted, the clean_recipient_email method will raise a validation error, and you'll see that your view and template display the invalid form as expected.

Upvotes: 1

Related Questions