简体   繁体   English

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

[英]Forbidden (403) CSRF verification failed. Request aborted

I created a custom template form for signup, and whenever I try to signup in my Django application. 我创建了一个用于注册的自定义模板表单,并在我尝试在Django应用程序中进行注册时创建了一个自定义模板表单。 i get this error message CSRF verification failed. 我收到此错误消息CSRF验证失败。 Request aborted. 请求中止。

I created a custom template form for signup, and whenever I try to signup in my Django application. 我创建了一个用于注册的自定义模板表单,并在我尝试在Django应用程序中进行注册时创建了一个自定义模板表单。 i get this error message CSRF verification failed. 我收到此错误消息CSRF验证失败。 Request aborted. 请求中止。

CSRF token missing or incorrect. CSRF令牌丢失或不正确。 Just really don't to do again. 只是真的不要再做。 I have not being able to by pass this error. 我无法通过此错误。

views.py 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 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 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 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>

Your index view, which is presumably the one that is rendering that template, is using render_to_response . 您的索引视图(大概是正在渲染该模板的视图)正在使用render_to_response You should not use that. 您不应该使用它。 Use render and pass the request: 使用render并传递请求:

return render(request, 'accounts/index.html', {})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 禁止(403)CSRF验证失败。 请求中止。 Django的 - Forbidden (403) CSRF verification failed. Request aborted. Django 禁止(403)CSRF验证失败。 请求使用django中止 - Forbidden (403) CSRF verification failed. Request aborted using django 禁止(403)CSRF验证失败。 请求中止。在Django中 - Forbidden (403) CSRF verification failed. Request aborted.in Django 禁止(403)CSRF验证失败。 请求中止 - Forbidden (403) CSRF verification failed. Request aborted 禁止(403)CSRF验证失败。 请求在Django 1.8.5中中止2 - Forbidden (403) CSRF verification failed. Request aborted 2 in django 1.8.5 禁止(403)CSRF验证失败。 请求在Django 1.11上中止 - Forbidden (403) CSRF verification failed. Request aborted on Django 1.11 禁止(403)CSRF验证失败。 请求中止。 即使使用{%csrf_token%} - Forbidden (403) CSRF verification failed. Request aborted. Even using the {% csrf_token %} 禁止Django注册(403)CSRF验证失败。 请求中止 - Django-registration Forbidden (403) CSRF verification failed. Request aborted 如何解决“禁止(403)CSRF验证失败。 请求中止。” Django中的错误 - How to fix “Forbidden (403) CSRF verification failed. Request aborted.” error in django 禁止 (403) CSRF 验证失败。 请求中止 - 与 Django 频道的实时聊天应用程序 - Forbidden (403) CSRF verification failed. Request aborted-Real time chat application with Django Channels
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM