大家好,所有你们都乐于助人(再见无帮助的人:D) . 我正在尝试在django(1.2.4)中创建用户,然后在保存后将其登录 . 我的问题是我收到了NotImplementedError并查看了由django.contrib.auth.models.AnonymousUser引发的回溯 . 这是我的视图代码的一部分:
def signup(request):
if request.method == 'POST': # If the form has been submitted...
p = request.POST
if not request.user.is_authenticated():
form = UserForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
form.save()
user=authenticate(username=p['username'],password=p['password'])
login(request,user)
return HttpResponseRedirect('/') # Redirect after POST
因此,在我看来,它正在尝试登录任何鼠标用户而不是我正在验证的用户,我该如何克服这个问题?
谢谢P.S.用户正在数据库中创建,它不会使用此代码登录 .
追溯:
环境:请求方法:POST请求URL:http:// localhost:8000 / signup / Django版本:1.2.4 Python版本:2.6.1已安装的应用程序:['django.contrib.auth','django.contrib.contenttypes ','django.contrib.sessions','django.contrib.sites','django.contrib.messages','django.contrib.admin','django.contrib.admindocs','django_extensions','REDACTED_APPs',已安装的中间件:('django.middleware.common.CommonMiddleware','django.middleware.locale.LocaleMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django .contrib.messages.middleware.MessageMiddleware','django.contrib.sessions.middleware.SessionMiddleware')
Traceback:
File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "REDACTED/views.py" in signup
19. login(request,user)
File "/Library/Python/2.6/site-packages/django/contrib/auth/__init__.py" in login
71. user.save()
File "/Library/Python/2.6/site-packages/django/contrib/auth/models.py" in save
430. raise NotImplementedError
Exception Type: NotImplementedError at /signup/
Exception Value:
3 回答
我认为这里发生的是
authenticate
正在返回None
,因此login
正在使用request.user
(AnonymousUser
) .看起来用于创建用户的信息与传递给
authenticate
的信息不同 . 我会仔细检查用户是否正确保存(尤其是密码) .Edit :从其他答案我看到您正在使用自定义用户表单 . 您应该使用
django.contrib.auth.forms.UserCreationForm
,它的save()
方法将正确设置密码 .以下没有为后人留下的 Value
轻松的是跳过这里的验证步骤(它没有添加任何重要的东西)
使用 form.save() 创建用户不是一个好方法...因为,由于密码以散列格式保存,因此使用密码集
简单地将未散列的数据写入数据库,并且django auth无法正确检查它...您需要的是:
不确定它是否有用,但最好提取如下表单字段:
从使用当前代码创建的用户,您可以将它们验证到系统中吗?
Here's an alternate way to create and login using a login form and creating the user manually: