问题描述
我使用微信openid登录django没有密码,但是自定义验证后端总是返回false,无法被“@login_required”正确识别访问视图。我是新手。非常感谢!
settings.py
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend','wechat.wechatAuth.WechatAuthBackend',]
from accounts.models import CustomUser
class WechatAuthBackend(object):
def authenticate(self,openid=None):
try:
return CustomUser.objects.get(openid=openid)
except CustomUser.DoesNotExist:
return None
def get_user(self,user_id):
try:
return CustomUser.objects.get(pk=user_id)
except CustomUser.DoesNotExist:
return None
views.py
from django.contrib.auth import authenticate,login
def weixinbind(request):
if request.user.is_authenticated: # Always returnfalse
return HttpResponse('yes login')
else:
print(request.user.is_authenticated)
return HttpResponse('no login')
def weixinbind_callback(request):
# test data
data = {"openid": "333"}
try:
auth = authenticate(data['openid'])
login(request,auth,backend='wechat.wechatAuth.WechatAuthBackend')
print(request.user.is_authenticated) # Can return correctly true
return HttpResponse('auth success')
except:
user = CustomUser(username = data['openid'],openid = data['openid'])
user.save()
return HttpResponse('create success')
调用login()时,可以正确返回“true”,但是在视图函数外访问“false”
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)