pptt
pptt

Reputation: 705

Django help me raise validation error

I am trying to create some kind of warning when someone enters the username that was already taken. However, all I manage to do is to redirect to static page where it says: username picked OR passwords do not match.

This is what I have written in my views.py:

def register_user(request):
    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success')
        else:
            return render_to_response('invalid_reg.html')

    args = {}
    args.update(csrf(request))

    args['form'] = MyRegistrationForm()
    print args
    return render_to_response('register.html', args)

and this is my forms.py:

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.set_password(self.cleaned_data["password1"])

        if commit:
            user.save()

        return user

I have literally no idea how do I give a proper warning to the user.

How can I implement some kind of validation error warning here?

Upvotes: 0

Views: 1199

Answers (1)

Claudiu
Claudiu

Reputation: 1829

You can add clean_ method to the form class to validate the username field:

def clean_username(self):
    username = self.cleaned_data.get('username')
    if username:
        user = User.objects.filter(username=username)
        if user.exists():
            raise forms.ValidationError(
                _('That username exists in our system. Please try another.'),
                code='unique_username'
            )
    return username

Afterwards you should rewrite your view function to pass the form object to the registration template:

def register_user(request):
    args = {}
    args.update(csrf(request))

    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success')
        else:
            args['form'] = form
            return render_to_response('register.html', args)

    args['form'] = MyRegistrationForm()
    print args
    return render_to_response('register.html', args)

I'm going to recommend that you find out how to display the error messages in the template by yourself.

These pages from Django's documentation should provide more insight:

Upvotes: 1

Related Questions