Django使用表单和csrf令牌来解决问题

时间:2012-04-18 03:54:05

标签: python django forms csrf django-csrf

我正在尝试使用一个非常简单的电子邮件表单。表单只有一个字段(电子邮件)。

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 (相关部分)

<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_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

当前结果:页面显示为没有涉及模板。我看到表单和提交按钮在那里,但没有电子邮件字段。也没有csrf隐藏字段。我一定错过了一些愚蠢的事......

1 个答案:

答案 0 :(得分:1)

假设这个:

from launchpage.models import EmailForm

不应该是from launchpage.forms import EmailForm

您遇到的另一个问题是{'form': form,}需要{'form': form}

最后,{{ form.email }}应该只是{{ form }}

最后提示 - 考虑使用自动发送相应请求上下文的render shortcut