Jeril
Jeril

Reputation: 8521

Django - Form validation not happening

The following is my code for creating a form:

from django import forms
class Register(forms.Form):
    username = forms.CharField(label='', max_length=64, required=True)
    firstname = forms.CharField(label='', max_length=64, required=True)
    surname = forms.CharField(label='sur name', max_length=64,  required=True)
    email = forms.EmailField()

The code of my view.py is as follows:

from .forms import Register
def register(request):
    form = Register()
    return render(request, 'app/register.html', {'form': form})

It is displaying the form in the webpage but its not validating the username, firstname, and surname; whereas its validating the emailfield.

I tried using the clean method, and my new forms.py is as follows:

from django import forms
class Register(forms.Form):
    username = forms.CharField(label='', max_length=64, required=True)
    firstname = forms.CharField(label='', max_length=64, required=True)
    surname = forms.CharField(label='sur name', max_length=64,  required=True)
    email = forms.EmailField()

    def clean_surname(self):
        data = self.cleaned_data['surname']
        if not data:
            raise forms.ValidationError("This field is required")
        return data

What might be the problem? Am I doing something wrong. Please help me with this, I am new to Django.

Upvotes: 0

Views: 1358

Answers (2)

GwynBleidD
GwynBleidD

Reputation: 20539

You're not passing post data into your form. It should look like this:

from .forms import Register
def register(request):
    form = Register(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        # your action when form is valid
    else:
        return render(request, 'app/register.html', {'form': form})

or None after request.POST will ensure that empty POST dictionary won't be passed into your form, so validation won't be triggered on first load of page - when there is nothing submitted.

Also, validation of email field probably comes from your browser, not from django.

Upvotes: 1

rafalmp
rafalmp

Reputation: 4068

To validate the form you need to populate it with data from the POST request and check if it's valid. Your view should look like this:

from .forms import Register

def register(request):
    if request.method == 'POST'  # process form data
        # create form instance, populate it with data
        form = Register(request.POST)
        # check if the data is valid
        if form.is_valid():
            # process/save the data
            # ...
            # then redirect to a new URL:
            return HttpResponseRedirect('/a/new/url/')
    else:
        # GET or other method, create a blank form
        form = Register()
    return render(request, 'app/register.html', {'form': form})

more in the documentation.

Upvotes: 4

Related Questions