user623990
user623990

Reputation:

Django troubles with forms and csrf tokens

I'm trying to get a pretty simple email form working. The form is only one field (email).

forms.py

from django import forms

class EmailForm(forms.Form):
    email = forms.EmailField()

views.py

from django.shortcuts import render_to_response
from django.core.mail import EmailMultiAlternatives
from django.template import RequestContext
from launchpage.models import EmailForm

def index(request):
    if request.method == 'POST':        
        form = EmailForm(request.POST)
        if form.is_valid():
            clean_data = form.clean_data
            # send an email
                    thank_you = "Thanks for signing up"
            return render_to_response('launch.html', {'thank_you': thank_you})
    else:
        form = EmailForm()
    return render_to_response('launch.html', {'form': form,}, context_instance=RequestContext(request))

launch.html (relevant part)

<div class="row-fluid">
    <div class="span12">
        {% if thank_you %}
             <div class="alert alter-info">
             {{ thank_you }}
             </div>
        {% else %}
            <form action="" method="post" class="form-horizontal">{% csrf_token %}
            Or stay updated by email (no spam, pinky swear) &nbsp;&nbsp;
            {{ form.email }}
            <button type="submit" class="btn">Submit</button>
        </form>
        {% endif %}
    </div>
</div>

middleware in settings.py

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

Current result: the page displays as if there was no templating involved. I see the form and the submit button is there, but no email field. Also no csrf hidden field. I must be missing something stupid...

Upvotes: 0

Views: 1348

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

Assuming that this:

from launchpage.models import EmailForm

shouldn't be from launchpage.forms import EmailForm

The other problem you have is {'form': form,} needs to be {'form': form}

Finally, {{ form.email }} should be simply {{ form }}

Final tip - consider using the render shortcut which sends the appropriate request context automatically.

Upvotes: 1

Related Questions