禁止(403)CSRF验证失败。请求中止

时间:2017-08-15 11:29:07

标签: python django

我为注册创建了一个自定义模板表单,每当我尝试在Django应用程序中注册时。我收到此错误消息CSRF验证失败。请求中止。

我为注册创建了一个自定义模板表单,每当我尝试在Django应用程序中注册时。我收到此错误消息CSRF验证失败。请求中止。

CSRF令牌丢失或不正确。 真的不要再做了。我无法通过此错误。

views.py

from django.shortcuts import render_to_response
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.template.loader import render_to_string
from .tokens import account_activation_token
from django.core.mail import EmailMessage
from .forms import SignupForm

def index(request):
    return render_to_response('accounts/index.html')
def register(request):
    if request.method == "POST":
        form = SignupForm(request.POST)
        if form.is_valid():
            username = request.POST.get('uname')
            first_name = request.POST.get("fname")
            last_name = request.POST.get("lname")
            email = request.POST.get("email")
            password = request.POST.get("password")
            dob = request.POST.get("dob")
            gender = request.POST.get("optradio")   

            new_user = Signup('username', 'first_name', 'last_name',   'email',    'password', 'dob', 'gender')
            new_user.is_active = False
            new_user.save()
            current_site = get_current_site(request)
            message = render_to_string('acc_active_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            })
            mail_subject = 'Activate your linkzone account.'
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(subject, message, to=[to_email])
            email.send()

            return HttpResponse('Please confirm your email address to    complete the registration')

def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except(TryError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        #return redirect('home')
        return HttpResponse('Thank you for your email confirmation. Now you can login in your account.')        

    else:
        return HttpResponse('Activation link is invalid')

models.py

from __future__ import unicode_literals
from django.contrib.auth.models import User
import uuid
from django.db import models

class Signup(User):
    GENDER = (
        ('M', 'Male'), 
        ('F', 'Female')
    )
    gender = models.CharField(max_length = 50, choices = GENDER, null = True)
    slug = models.SlugField('slug', max_length = 100, unique=True)

    def __unicode__(self):
        return self.firstname

    def save(self, **kwargs):
        slug_str = "%s, %s" % (self.user, self.uuid.uuid4())
        unique_slugify(self, slug_str)
        super(Signup, self).save(**kwargs)

forms.py

from django.forms import ModelForm
from .models import Signup
from django.contrib.auth.forms import UserCreationForm
from django import forms

class SignupForm(UserCreationForm):
    email = forms.EmailField(max_length = 200, help_text = 'Required')

    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)

class Meta:
    model = Signup
    fields = ("username", "email", "password1", "password2")

base.html文件

<form method = 'post' action = "{% url 'user-register' %}">
{% csrf_token %} 
    <input type="text" name = "uname" class = "form-control" placeholder="User Name" required>
    <input type="text" name = "fname" class = "form-control" placeholder="First Name" required>
    <input type="text" name = "lname" class = "form-control" placeholder="Last Name" required>
    <input type="email" name = "email" class = "form-control" placeholder="Email" required>
    <input type="password" name = "password1" class = "form-control" placeholder="Password" required>
    <input type="password" name = "password2" class = "form-control" placeholder="Confirm Password" required>
    <input type="date" name = "dob" class="form-control" required>
    <div class="radio" required>
        <label><input type="radio" name="optradio" value="M">Male</label>&nbsp; &nbsp;
        <label><input type="radio" name="optradio" value="F">Female</label>
    </div>
    <button type="submit" name="register" id="btn-bevel" class="center-block">Sign Up</button>
</form>

1 个答案:

答案 0 :(得分:1)

您的索引视图(可能是呈现该模板的视图)正在使用render_to_response。你不应该使用它。使用render并传递请求:

return render(request, 'accounts/index.html', {})
相关问题