I'm attempting to list a validation error on my HTML template if the form on that template isn't properly submitted. My forms.py file includes a function (clean_email) that will catch any string that's entered that doesn't include an "@" symbol, and it actually works. Therefore, any form that I attempt to submit without an "@" character in the email field won't be submitted.
Unfortunately, the error isn't displayed as it should be on my HTML template. The code for displaying it is in line 15 of contact.html (contactform.errors ). This code doesn't produce any results. Here are the relevant files:
Models.py
from __future__ import unicode_literals
from django.db import models
class Contact(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
phone_number = models.CharField(max_length=30, blank=True)
email = models.CharField(max_length=50)
message = models.TextField(default=" ")
Forms.py
from models import Contact
from django.forms import ModelForm
from django.core.exceptions import ValidationError
from django import forms
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = "__all__"
def clean_email(self):
email = self.cleaned_data["email"]
if "@" not in email:
raise ValidationError("Not an Email Address")
return email
Views.py
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from forms import ContactForm
def contact(request):
contactform = ContactForm()
if request.method == "POST":
contactform = ContactForm(request.POST)
if contactform.is_valid():
message = contactform.save(commit=False)
message.save()
return HttpResponseRedirect(reverse("contact"))
else:
print(contactform.errors)
contactform = ContactForm()
return render(request,"contact_form/contact.html",{"contactform":contactform})
Finally, Contact.HTML
{% block content %}
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static "css/main.css" %}">
<link rel="stylesheet" href="{% static "css/contact.css" %}">
<div class="outer">
<form method="POST" action="">
{% csrf_token %}
<ul>
<li>
<label = for="email">Email</label>
{{ contactform.email }}
{{ contactform.errors }}
</li>
</ul>
<input type="submit" value="Submit Form"/>
</form>
</div>
{% endblock %}
Any ideas/help is appreciated, thanks!
Aucun commentaire:
Enregistrer un commentaire