CSRF验证失败。请求中止Django 1.6

时间:2014-03-16 00:19:45

标签: python django

尝试构建时尚技术应用程序,当我设置表单,视图,模型和模板时,一切似乎都很好,我得到了CSRF验证失败错误。关于我做错了什么的任何线索?

models.py:

from django.db import models
from django.contrib.auth.models import User


class ProfileUser(models.Model):
    user = models.OneToOneField(User,unique=True)
    birthday = models.DateField(null=True,blank=True)
    city = models.CharField(max_length=50,blank=True)
    state = models.CharField(max_length=50,blank=True)

    user_title = models.CharField(max_length=254, verbose_name="Influencer Level", blank=True)
    user_points = models.IntegerField(null=False, verbose_name="Influence Credit", blank=True)
    picture = models.ImageField(upload_to='images', blank=True)


    #admin level and additional infomation
    is_staff = models.BooleanField(default=False)

    #Override the _unicode_() method to return out something meaningful
    def _unicode_(self):
        return self.user.username

forms.py:

#coding=utf-8
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.forms import extras
from models import ProfileUser



###### Login for users ###########
# class LoginForm(forms.Form):
#     username=forms.CharField(label=_(u"username"),max_length=30,widget=forms.TextInput(attrs={'size': 20,}))
#     password=forms.CharField(label=_(u"password"),max_length=30,widget=forms.PasswordInput(attrs={'size': 20,}))

#     class Meta:
#         """docstring for Meta"""
#         model = User


###### Registration for users ###########
class RegisterForm(forms.ModelForm):
    email=forms.EmailField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Email', 'required':True}))    
    username=forms.CharField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Username','required':True}))
    password=forms.CharField(max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Password','required':True}))
    password2=forms.CharField(max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Re-Enter Password','required':True}))


    class Meta:
        """The model that is extened from django models and the fields below are specified to prevent abstraction"""
        model = User
        fields = ('email', 'username', 'password', 'password2')



    def clean(self):
        cleaned_data = super(RegisterForm, self).clean()
        email = cleaned_data.get('email')
        username = cleaned_data.get('username')
        password = cleaned_data.get('password')
        password2 = cleaned_data.get('password2')

        #check if username exist
        user = User.objects.filter(username=username)
        if user:
            raise forms.ValidationError("this username is already exsist")


        #check for password and re-enter password
        if password != password2:
            raise forms.ValidationError("Password does not match")

        #check for email is system
        emails = User.objects.filter(email=email)
        if email:
            raise forms.ValidationError("this email is already registered")

        return cleaned_data

views.py:

#coding=utf-8
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login as auth_login ,logout as auth_logout
from django.utils.translation import ugettext_lazy as _
from forms import RegisterForm
from models import ProfileUser


###### Login for users ###########
# def login(request):
#     template_var={}
#     form = LoginForm()    
#     if request.method == 'POST':
#         form = LoginForm(request.POST.copy())
#         if form.is_valid():
#             _login(request,form.cleaned_data["username"],form.cleaned_data["password"])
#             return HttpResponseRedirect(reverse("login"))
#     template_var["form"]=form        
#     return render_to_response("registration/login.html",template_var,context_instance=RequestContext(request))


# def _login(request,username,password):
#     ret = False
#     user = authenticate(username=username,password=password)
#     if user:
#         if user.is_active:
#             auth_login(request,user)
#             ret=True
#         else:
#             messages.add_message(request, messages.INFO, _(u'user is not active'))
#     else:
#         messages.add_message(request, messages.INFO, _(u'Incorrect username or password'))
#     return ret


###### Registration for users ###########
def register(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('success'))

    form = RegisterForm()  # this will is used in the GET request  
    if request.method=="POST":
        form=RegisterForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data["username"],
                email=form.cleaned_data["email"],
                password=form.cleaned_data["password"]
            )
            user.is_active = True
            user.save()
            return redirect('base')
        else:
            return render_to_response("registration/signup.html",context_instance=RequestContext(request))

            person = authenticate(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password']
            )

            login(request, person)
            return HttpResponseRedirect(reverse("success"))    

    return render_to_response("registration/signup.html",context_instance=RequestContext(request))

模板:

{% extends 'home/base.html' %}
{% block title %}Signup with Indieitude{% endblock title %}

{% block search %}
{% endblock search %}


{% block space %}
<div  class="space-registration"></div>
{% endblock space %}

{% block signup %}  
<div id="content"> 
    <div class="block">
        <div class="box-login">
            <div class="head">
                 <h2 class="heading-title">Start Discovering</h2>

                <p align="center"><em>Log in with your Facebook</em>
                </p>
            </div>
            <div class="socialconnect"> <a href="#" class="facebook">Log in with Facebook</a>

            </div>
            <p align="center"><em>Or signup with your email & name</em>
            </p>
            <div class="box-form">
                <form action="" method="post">{% csrf_token %}


                    <p>
                        {{form.email}}
                    </p>
                    <p>
                        {{form.username}}
                    </p>
                    <p>
                        {{form.password}}
                    </p>
                    <p>
                        <!-- <input type="password" id="" name="" required="required"  class="text-input" placeHolder="Re-Enter Password" /> -->
                    </p>
                    <p class="agree">By signing up, I agree to Indieitude's <a href="#">Terms of Service</a> & <a href="#">Privacy Policy</a>
                    </p>
                    <p>
                        <input type="submit" name="submit" value="register" class="button large bold">
                    </p>
                </form>
            </div>
            <div class="footer">
                 <h2 class="heading-title" align="center">Already have an account? <a href="{% url "profiles.views.login" %}">Login</a></h2>
            </div>
        </div>
    </div>
</div>
{% endblock signup %}  

1 个答案:

答案 0 :(得分:1)

views.py

from django.core.context_processors import csrf


def register(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('success'))

    if request.POST:
        form=RegisterForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data["username"],
                email=form.cleaned_data["email"],
                password=form.cleaned_data["password"]
            )
            user.is_active = True
            user.save()
            return redirect('base')
    else:
        form = RegisterForm()    

    args = {'form' : form}
    args.update(csrf(request))
    return render_to_response("registration/signup.html", args)