Django中的CSRF令牌问题

时间:2014-12-01 10:16:08

标签: python django python-2.7

我试图为用户创建注册页面,但是从Django(v 1.7.1)中获取错误:

  

失败原因:       未设置CSRF cookie。

我确定,我的电脑上允许使用cookie(Chrome浏览器)。添加{%csrf_token%}并不能解决我的问题。也许有人建议我,如何解决这个问题?

部分来自我的register.html:

<div class="container">
    <form action="." class="form-signin" method="post">
        {% csrf_token %}
        <h4 class="form-signin-heading">Register new user</h4>
        {{ form.login }}
        {{ form.login.errors }}
        {{ form.password }}
        {{ form.password.errors }}

        {{ form.address }}
        {{ form.address.errors }}
        {{ form.phone }}
        {{ form.phone.errors }}
        {{ form.postcode }}
        {{ form.postcode.errors }}

        {{ form.email }}
        {{ form.email.errors }}
        <button class="btn btn-small btn-primary" type="submit">Register me</button>
    </form>
</div>

RegisterForm.py

# -*- coding: utf-8 -*-
from django import forms

from mainws.models.User import User

class RegisterForm(forms.Form):
    login = forms.CharField(min_length=3, max_length=50, required=True,
                            error_messages={'required': 'Enter login'},
                            widget=forms.TextInput(attrs={'placeholder': 'login',
                                                          'class': "input-block-level"}))
    password = forms.CharField(min_length=6, max_length=50, required=True,
                               error_messages={'required': u'Enter password'},
                               widget=forms.TextInput(attrs={'placeholder': 'password',
                                                             'class': "input-block-level",
                                                             'type': 'password'}))
    address = forms.CharField(min_length=5, max_length=255, required=True,
                              error_messages={'required': u'Enter address'},
                              widget=forms.TextInput(attrs={'placeholder': 'address',
                                                            'class': "input-block-level"}))
    phone = forms.CharField(min_length=7, max_length=25, required=True,
                            error_messages={'required': u'Enter phone'},
                            widget=forms.TextInput(attrs={'placeholder': 'phone',
                                                          'class': "input-block-level"}))
    postcode = forms.CharField(min_length=2, max_length=25, required=True,
                               error_messages={'required': u'Enter postcode'},
                               widget=forms.TextInput(attrs={'placeholder': 'postcode',
                                                             'class': "input-block-level"}))
    email = forms.EmailField(min_length=5, required=True,
                             error_messages={'required': u'Enter email'},
                             widget=forms.TextInput(attrs={'placeholder': 'email',
                                                           'class': "input-block-level"}))

    def clean(self):
        super(RegisterForm, self).clean()

        typed_login = self.cleaned_data['login']
        if User.objects.filter(login=typed_login).exists():
            raise forms.ValidationError('This user already registered!')
        return self.cleaned_data

RegisterController.py

from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.base import View
from django.shortcuts import render_to_response

from mainws.forms.RegisterForm import RegisterForm


class RegisterController(View):

    def get(self, request, *args, **kwargs):
        form = RegisterForm()
        return render_to_response('user/register.html', locals())

    def post(self, request, *args, **kwargs):
        form = RegisterForm(request.POST)
        if form.is_valid():
            #return HttpResponseRedirect('/login')
            return HttpResponse('OK!', locals())
        else:
            return HttpResponse('all not valid!', locals())

1 个答案:

答案 0 :(得分:2)

您在render_to_response中未使用RequestContext的错误。这就是csrf_token为空的原因。

要在您的视图中利用CSRF保护,请按以下步骤操作:

  1. 添加&#39; django.middleware.csrf.CsrfViewMiddleware&#39;到MIDDLEWARE_CLASSES。的完成
  2. 在元素中使用csrf_token标记。的完成
  3. 确保&#39; django.core.context_processors.csrf&#39;正在使用上下文处理器: 在您的视图中使用RequestContext或手动执行。 未完成
  4. 有关详情,请参阅docs