我想使用标准Django方法更改用户电子邮件,但在更改电子邮件之前,表单和数据库中的密码必须匹配。而且我得到403错误CSRF token missing or incorrect.
这是我的form
:
class ChangeMailForm(forms.Form):
password = forms.CharField(label = (u'Podaj hasło'), widget=forms.PasswordInput(render_value=False))
email = forms.EmailField(label = (u'Podaj nowy adres email'))
def clean_email(self):
mail = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise ValidationError("Taki email jest w bazie")
return mail
我的view
:
def ChangeEmail(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/')
if request.method == 'POST':
form = ChangeMailForm(request.POST)
if form.is_valid():
usr = request.user
u = User.objects.filter(username=usr)
if not User.objects.filter(username=usr).check_password(form.cleaned_data['password']):
return HttpResponseRedirect('/')
mail = form.cleaned_data['email']
u.new_email(mail)
u.save()
else:
return render_to_response('changeemail.html', {'form':form},context_instance=RequestContext(request))
else:
form = ChangeMailForm()
return render_to_response('changeemail.html', {'form':form}, context_instance=RequestContext(request))
和我template
的一部分:
<form action="" method="post">
{% csrf_token %}
{% if form.errors %}<p id="correct">Popraw następujące pola:</p>{% endif %}
<table id="change">
<tr>
<td {% if form.password.errors %} class="error" {% endif %}>Podaj hasło:</td>
<td>{{ form.password }}</td>
</tr>
<tr>
<td {% if form.email.errors %} class="error" {% endif %}>Podaj nowy adres:</td>
<td>{{ form.email }}</td>
</tr>
</table>
<div id="sub">
<input type="submit" value="Wykonaj" alt="login" id="submit" />
非常感谢任何帮助。
编辑:在放入@csrf_exempt装饰后添加了追溯
Request Method: POST
Request URL: http://127.0.0.1:8000/changeemail/
Django Version: 1.7.1
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'dailyresults',
'trainingresults',
'athlete',
'easy_pdf')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "D:\Programy\Python27\lib\site-packages\django-1.7.1-py2.7.egg\django\core\handlers\base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Programy\Python27\lib\site-packages\django-1.7.1-py2.7.egg\django\views\decorators\csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "D:\Inz\trening\athlete\views.py" in ChangeEmail
93. if not User .objects.filter(username=usr).check_password(form.cleaned_data['password']):
异常类型:/ changeemail /上的AttributeError 例外值:&#39; QuerySet&#39;对象没有属性&#39; check_password&#39;
答案 0 :(得分:1)
您需要更改此行:
u = User.objects.filter(username=usr)
if not User.objects.filter(username=usr).check_password(...):
到此:
u = User.objects.filter(username=usr).first()
if u and u.check_password(...):
...
为什么它会在第一种方法中引发错误是因为u
是列表中的查询集,它本身没有check_password
方法。但您可以使用queryset().first()
访问用户对象或将其u[0]
切片并获取用户对象(当然您需要验证是否存在,否则它将是[])。
请确保您的请求中确实存在csrf_token
,您可以使用记录并查看:
import logging
...
#your view
logging.info('request MEAT for csrf: %s', request.META.get('CSRF_COOKIE'))
看看它是否存在。
您也可以尝试清除浏览器缓存,或者使用其他浏览器(新会话或私有会话)进行测试,看看是否仍然出现错误。
如果您需要更新电子邮件字段,只需使用普通模型保存方法:
# above code... and being verified ...
u.email = form.cleaned_data['email']
u.save()
那就是它。