Search code examples
djangodjango-formsdjango-templatesautosuggestvalidationerror

How to send additional data to the template when Django ValidationError occurred on a specific field?


Let us say, I have a Django Form - XYZ which had fields A, B, C. Field B is username field, when a particular username already exists, Validation Error occurs and throws back a message. Along with that I want to send some auto-suggested username-dict to the template. As per my understanding, i can only send as Field Errors and Non-Field errors.

def clean_B(self):
        B = self.cleaned_data['B']
        if address.objects.filter(B=B).exists():
            raise forms.ValidationError("Username already exists")
        return B

I tried to add another error using Form.add_error() and Django doesn't allow multiple errors in a single dict per field or Non_field errors.

How can i do this?

Thanks!


Solution

  • I think you can use django messages framework to show your message with suggestions to user.

    from django.contrib import messages
    
    ...
    
    def clean_B(self):
        B = self.cleaned_data['B']
        if address.objects.filter(B=B).exists():
            # In __init__ method of the form, you should store request as property
            messages.info(self.request, 'You should use another username, i.e. John')
            raise forms.ValidationError('Username already exists')
        return B
    

    And then, somewhere in your template, output message:

    {% if messages %}
    <ul class="messages">
        {% for message in messages %}
        <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
        {% endfor %}
    </ul>
    {% endif %}