0

I'm taking advantage of these built-in Django forms and I am running into a small issue.

  • class AdminPasswordChangeForm
  • class AuthenticationForm
  • class PasswordChangeForm
  • class PasswordResetForm
  • class SetPasswordForm
  • class UserChangeForm
  • class UserCreationForm

For example, the UserCreationForm generates several validation errors which I can display in the my template using tags such as {{ form.errors }} or even ones related to a specific field such as {{ form.username.errors }}.

I know how to customize the styling of these error messages, but how can I customize the text? I have been able to simply check if an error exists with a conditional statement such as {% if form.password.errors %} and place my own custom text in that block. However, that leaves me blind to the type of error that was raised.

For instance, I want to be able to identify if the triggered error was a duplicate_username or a password_mismatch so I can write my own error in the template.

Any help would be appreciated!

1 Answer 1

2

Generally speaking, you can customize the clean method like below:

class EventDetailsForm(form.ModelForm):
    class Meta:
        model = Event
        fields = ('name',)
        layout = (
                Fieldset('',
                'name',),
                )

    def clean_name(self):
        event_name = self.cleaned_data['name']
        if Event.objects.filter(name=event_name, status='Live').\
                exclude(id=self.instance.id).exists():
            raise forms.ValidationError('This Name is already in use')
        else:
            return event_name

So to re-use django's form, just subclass it, add additional validation logic and call that form in your view function.

Sign up to request clarification or add additional context in comments.

4 Comments

Is that an ADDITIONAL check? Or does adding a clean method in a subclass of the original form override/replace the existing clean methods?
It will override it. So you can copy the existing validation methods and add in your own custom logic. Not super DRY but gets the job done.
Not sure if I'm misunderstanding things, but I just tried creating a subclass of UserCreationForm and AuthenticationForm and the original logic was still completely present. It would only change if I created functions with the same names to replace the original ones.
That is exactly the expected behaviour and what I meant. Som subclass the form, copy paste the clean method from django into your custom form. Add in the extra custom validation logic you require into that clean method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.