Form Validation Error NOT Raised When Form Is Submitted

1,360 views
Skip to first unread message

Chris Kavanagh

unread,
Dec 22, 2016, 8:14:36 PM12/22/16
to Django users
I have a model form called "ContactForm" that has an email field. I created a custom forms.ValidationError in "clean_email" method

 which checks to see if the email is already in the database , however it's never raised on submit.


 When submit is called, the view runs and I get the error "The view customer.views.send_email didn't return an HttpResponse object.

 It returned None instead", because it's not being passed an actual email. . 

I don't understand why the forms.ValidationError isn't stopping it from being submitted? The query in the "clean_email" works fine, so that's not the problem.

I've used this same code before with no problems. I'm sure it's something easy I'm forgetting or missing, but any help is GREATLY appreciated. .

Note: I am using django crispy forms


#Model:
class Customer(models.Model):
    email = models.EmailField(max_length=70,blank=False)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
    ordering = ('email',)

def __unicode__(self):
return self.email




#Form:
class ContactForm(forms.ModelForm):

class Meta:
model = Customer
fields = ['email']

def clean_email(self):
email = self.cleaned_data['email']
cust_email = Customer.objects.filter(email=email).count()
if cust_email:
raise forms.ValidationError('This email is already in use.')
return email




#View:
def send_email(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            email = cd['email']
            new_email = form.save(commit=True)
            to_email = form.cleaned_data['email']   # cd['email']
            subject = 'Newsletter'
            from_email = settings.EMAIL_HOST_USER
            message = 'You Are Now Signed Up For BenGui Newsletter!'
            #send_mail(subject, message, from_email, [to_email,], fail_silently=False)
            return redirect('home')
    else:
        return render(request, 'home.html', context)



#customer.urls:

urlpatterns = [    
    url(r'^send-email/$', views.send_email, name='send_email'),
    ]


#Template:

<form action="{% url 'customer:send_email' %}" method="post">
                    {% csrf_token %}
                    {{ form|crispy }}
                <input class='btn btn-success btn-lg btn-block' type='submit' value='Submit'></input>
            </form>

Vijay Khemlani

unread,
Dec 23, 2016, 2:30:22 AM12/23/16
to django...@googlegroups.com
I'm not following

If you submit the form with incorrect information (non unique email) then your view does not return anything because form.is_valid() returns False

Validation errors don't prevent the form from being submitted, they prevent the form from validation (making form.is_valid() return False and adding values to form.errors)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8ff5313f-3783-4897-afa7-5edd4fe1b436%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Chris Kavanagh

unread,
Dec 23, 2016, 2:49:21 AM12/23/16
to Django users
Yeah, I was wrong Vijay. For some odd reason I thought the ValidationError would catch it BEFORE submitted. . .

I re-read the docs and saw I was wrong. .

In other words, I I try to submit the form with the input field empty, I get a small pop up error saying "Please Enter An Email".

Or, if I use an invalid email format, I get the same popup error saying "Please Enter An Email Address."

Is there a way to do this with this (with django)?
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

Vijay Khemlani

unread,
Dec 23, 2016, 2:55:05 AM12/23/16
to django...@googlegroups.com
if the form is not valid then form.errors should contain human-readable errors for each field, including the one you validate yourself (the string inside the raise ValidationError call), you can return that.

To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

Chris Kavanagh

unread,
Dec 23, 2016, 3:23:20 AM12/23/16
to Django users
I got it working Vijay! Thank you so much for your help, and have a great Christmas!!
Reply all
Reply to author
Forward
0 new messages