Search code examples
djangoformsdjango-formsmodelformvalidationerror

Unable to raise Validation Error from ModelForm on the browser (DJANGO)


I am trying to raise an error and show it on the browser if the user enter submit an input of an email already inside the database. For some reasons, instead of raising the error, nothing is saved in the database but the user is redirected to the page i set to redirect to.

I want to be able to stop the user and raise the error if email exists in the database.

Model:

class Foo(models.Model):
    full_name = models.CharField(max_length=50)
    email = models.EmailField(max_length=50, blank=False)
    phone_number = models.CharField(max_length=10, blank=False)

Forms.

from django import forms

from .models import Foo

class FooModelForm(ModelForm):
    class Meta:
        model = Foo
        fields = ['full_name', 
                'email',
                'phone_number']
        help_texts = {'full_name': ('Required'),
                    'email': ('Required'),
                    'phone_number': ('Required')}

    def clean_email(self):
        '''
        Check if exists in database.
        '''
        email = self.cleaned_data.get('email')
        try:
            match = Foo.objects.get(email=email)
        except Foo.DoesNotExist:
            return email

        # raise forms.ValidationError('This email is already in use.')

from django.shortcuts import render, redirect
from snippets.models import Foo
from snippets.forms import FooModelForm



def index(request):
    if request.method == 'POST':
        form = FooModelForm(request.POST)
        if form.is_valid():
            form.save()
        return redirect('snippets:form-sent')

    else:
        form = FooModelForm()

    context = {'form':form}
    return render(request, 'snippets/index.html', context)  

HTML

<form method="post" id="form">
    {% csrf_token %}
    {{ form|crispy }}
    <div class="text-center">
       <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</form>

I am totally lost here as simple as it may be.

Any help would be much appreciated.


Solution

  • You have a simple indentation problem. Your return redirect... line is always called on POST, even if the form is not valid. Move it one indent further, so that it is inside the is_valid block.