私信  •  关注

Dingo

Dingo 最近回复了
11 年前
回复了 Dingo 创建的主题 » authenticate()不能检验password

已经解决了。问题主要是is_valid()。一般情况下,自己写一个form,然后调用其is_valid()的方法,只会检查表单输入是否符合格式,比如是不是超出定义的长度限制。而我用的是django自带的表单:

from django.contrib.auth.models import User
class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ['username', 'password']

直接使用django自带的user的话,它的is_valid()是重写了的,调用is_valid()就不单单是检查表单格的格式了,还要检查是否有重复用户。所以注册的表单用它的user比较好,可以防止重复的注册。登陆的表单就不要用了,用自己写的吧。 谢谢各位的回答。

11 年前
回复了 Dingo 创建的主题 » authenticate()不能检验password

我也被这问题弄晕了。问题的关键是,函数为什么不是必然执行的。因为login()是表单页面的处理函数,所以不论表单怎么填写,都应该执行函数。执行函数的话“return HttpResponse(user)# 这里应该会出错”这句一定会执行到。但是用户名存在的话,根本没有执行这句话。说明很有可能没有执行函数。为什么不执行函数呢?我也晕了

11 年前
回复了 Dingo 创建的主题 » authenticate()不能检验password

唉,我发现了个更奇怪的事情。整个函数如下

def login(request):
    if request.method == 'POST':
        ruser = UserForm(request.POST)
        if ruser.is_valid():
            cduser = ruser.cleaned_data    
            #user=authenticate(username='abc',password='123') 这里注释了
            return HttpResponse(user)# 这里应该会出错
            if user is not None:
                return HttpResponse('success')
            else:
                return HttpResponse('wrong')
    else:
        ruser = UserForm()
    return render_to_response('login.html',{'user':ruser},context_instance=RequestContext(request))

当表单用户名不存在时,的确会出错。但是用户名存在的话,仍然停留在原界面。而且从服务器请求记录来看,两种情况都收到了POST的请求。

11 年前
回复了 Dingo 创建的主题 » authenticate()不能检验password

对,不过和密码没有关系。只要用户名不对,就可以打印,用户名数据库里有的话就不能打印。

11 年前
回复了 Dingo 创建的主题 » authenticate()不能检验password
user=authenticate(username='abc',password='123') 
return HttpResponse(user)
if user is not None:
    return HttpResponse('success')
else:
    return HttpResponse('wrong')

试了一下,结果这样,当表单用户名不是abc时,返回的页面是abc。用户名是abc时,停留在原页面。就是说后者程序没有运行到第一个return。而且只要是数据库里有的用户名提交表单后都停留在原页面。

11 年前
回复了 Dingo 创建的主题 » authenticate()不能检验password

经测试,与浏览器和系统无关。可能是缓存之类的?

11 年前
回复了 Dingo 创建的主题 » authenticate()不能检验password

现在是这样的:

user=authenticate(username='abc',password='123') #这个用户存在
if user is not None:
    return HttpResponse('success')
else:
    return HttpResponse('wrong')

然后每次提交表单都应该显示success吧。 可我的实际情况是,若用户名不是abc,提交表单后可以到success页面。若用户名是abc,提交后停留在原页面。这样的情况很奇怪。我用的是火狐11.0,ubuntu12.04.

11 年前
回复了 Dingo 创建的主题 » authenticate()不能检验password

如果认证成功,它返回一个 User 对象。 如果密码无效,它返回一个 None 。 是这样吗?