我有一个Django项目,其中尝试“更新”(单击按钮)会导致以下错误:
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
我查看了各种问题和答案,这些建议表明添加RequestContext是解决方案,但是我尝试了一些针对我的代码量身定制的解决方案,但是仍然无法使其正常工作。
原始代码 views.py 在下面
#USERS (register) view.py
from django.shortcuts import render,redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages #this allows us flash messages for testing
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm
from .forms import UserUpdateForm
from .forms import ProfileUpdateForm
from django.contrib.auth.decorators import login_required
def register(request):
if request.method =='POST':
#this UserRegisterForm is created in forms.py and inherits from UserCreationForm (the ready made form)
form = UserRegisterForm(request.POST) #create a form that has the data that was in request.POST
if form.is_valid(): #is the form valid (do you have a username like this already, passwords match?
form.save()
username = form.cleaned_data.get('username')
messages.success(request,f'Account created for {username}, you can now login.')
return redirect('login')
else:
form =UserRegisterForm() #if the form input is invalid, render the empty form again
return render(request, 'users/register.html',{'form':form})
@login_required #this is a decorator (adds functionality to an existing function)
def profile(request):
if request.method =='POST':
u_form =UserUpdateForm(request.POST,instance=request.user)
p_form =ProfileUpdateForm(request.POST, request.FILES,instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request,f'Your Account has been directed')
return redirect('profile')
else:
u_form =UserUpdateForm(instance=request.user)
p_form =ProfileUpdateForm(instance=request.user.profile)
context={
'u_form': u_form,
'p_form': p_form
}
return render(request,'users/profile.html',context)
如上所述,我也尝试过:
return render(request,'users/profile.html',context_instance=RequestContext(request))
我还尝试将以下内容添加到导入中
from django.shortcuts import get_object_or_404, render,redirect
注意:我不希望尝试使用“删除中间件”替代方法。
下面是 profile.html 文件代码,据我所知,我正确地包含了CSRF令牌:
{% extends "socialmedia/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
<form method="POST" enctype="multipart/form-data>
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile Information</legend>
{{u_form|crispy}}
{{p_form|crispy}}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update....</button>
</div>
</form>
</div>
{% endblock content %}
最后,关于上下文,这里是 forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm): #form that inherits from the usercreationform
email = forms.EmailField()
class Meta:
model = User
#when this form validates it creates a new user
#type the fields to be shown on your form, in that order.
fields = ['username','email','password1','password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username','email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model= Profile
fields=['image']
问题:是什么导致错误,我需要在代码中添加/更改内容吗?
我还遇到了一个关于StackOverflow的回答,它说:“问题是您没有返回结果。请记住,该视图是一个函数。您需要返回render_to_response(...),而不仅仅是调用它(还为什么通过删除CSRF却没有返回HttpResponse错误)“ ....有人可以在我的上下文中解释这一点吗?我也不明白这意味着什么或如何实现。
答案 0 :(得分:1)
它似乎应该可以工作,但是我注意到您似乎在此处末尾缺少引号
<form method="POST" enctype="multipart/form-data>