Reputation: 5714
I get the follow error no matter what way I do achieve my forms. This happens when I go to the URL of my form.
forms.py
class ContactForm(forms.ModelForm):
class Meta:
model = ContactUs
fields = ('name', 'email', 'phone', 'message')
models.py
class ContactUs(models.Model):
name = models.CharField(max_length=50, blank=True)
email = models.EmailField()
phone = models.CharField(max_length=15, blank=True)
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
class Meta:
verbose_name_plural = "Contact Us"
views.py
def contact(request):
if request.method == "POST":
form = ContactForm(request.POST or None)
errors = None
if form.is_valid():
ContactUs.objects.create(
name = form.cleaned_data.get('name'),
email = form.cleaned_data.get('email'),
phone = form.cleaned_data.get('phone'),
message = form.cleaned_data.get('message'),
created_at = form.cleaned_data.get('created_at')
)
return HttpResponseRedirect("/s/")
if form.errors:
errors = form.errors
template_name = 'contact_us.html'
context = {"form": form, "errors": errors}
return render(request, template_name, context)
urls.py
url(r'^contacts/$', views.ContactForm, name='contact_form'),
html
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-warning">Submit</button>
</form>
Thanks in advance!
Upvotes: 2
Views: 3023
Reputation: 27523
well thats becuase you are only checking POST and not anything for GET method
def contact(request):
template_name = 'contact_us.html'
if request.method == "POST":
form = ContactForm(request.POST or None)
errors = None
if form.is_valid():
ContactUs.objects.create(
name = form.cleaned_data.get('name'),
email = form.cleaned_data.get('email'),
phone = form.cleaned_data.get('phone'),
message = form.cleaned_data.get('message'),
created_at = form.cleaned_data.get('created_at')
)
return HttpResponseRedirect("/s/")
if form.errors:
errors = form.errors
context = {"form": form, "errors": errors}
return render(request, template_name, context)
else:
form = ContactForm()
return render(request, template_name, {'form':form})
and also change your url to
url(r'^contacts/$', views.contact, name='contact_form'),
Upvotes: 3
Reputation: 599826
You've pointed your URL to the form, not the view. It should be:
url(r'^contacts/$', views.contact, name='contact_form'),
Note once you've fixed this you will have another problem, as your view does not return anything for a GET request.
Upvotes: 5