manosim
manosim

Reputation: 3690

Django contact form doesn't show up

I'm trying to make the contact form that is found in the django tutorial but unfortunately the form doesn't show up with {{ form }}. The only thing that shows up is the submit button. Below you can find the code:

forms.py

from django import forms
# Create your forms here.

class ContactForm(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from contact.forms import ContactForm
# Create your views here.

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']

            recipients = ['[email protected]']

            send_mail(name, email, message, recipients)
            return HttpResponseRedirect(reverse('contact-thanks'))
    else:
        form = ContactForm()
    return render(request, 'contact/contact-form.html', {
        'form': form,
    })

contact-form.html

<form action="/contact/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

Upvotes: 0

Views: 198

Answers (3)

manosim
manosim

Reputation: 3690

After two days, I finally got the solution. The error was in the urls.py file. (So next time I will include urls.py as well) Thanks for helping guys!

I was using a TemplateView:

url(r'^$', TemplateView.as_view(template_name='contact/contact-form.html'), name="contact-form"),

Instead of adding the view I created so that it would be possible to show and process the form.

url(r'^$', 'contact.views.contact', name="contact"),

Upvotes: 0

hizbul25
hizbul25

Reputation: 3849

Its not good practice to use template_name inside url.
try with this :

url(r'^/contact$','appname.views.contact',name='contact')

Upvotes: 1

Anish Shah
Anish Shah

Reputation: 8169

This should work..

from django.core.context_processors import csrf

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']

            recipients = ['[email protected]']

            send_mail(name, email, message, recipients)
            return HttpResponseRedirect(reverse('contact-thanks'))
    else:
        form = ContactForm()

    args = {'form' : form}
    args.update(csrf(request))
    return render(request, 'contact/contact-form.html', args)

Upvotes: 0

Related Questions