我有一个简单的聊天应用程序,我自定义身份验证后端只使用名称。到目前为止,它正在运行,用户使用Django login()登录。
现在我遇到了一个问题,即分配一个用户出现此错误,然后停止该应用程序的其余部分:
ValueError: Cannot assign "<SimpleLazyObject:
<django.contrib.auth.models.AnonymousUser
object at 0x7f7db7b71e80>>": "PChat.user" must be a "User" instance.
View.py
from chatbot import settings
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse,HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login
from Pchat.models import PChat
from django.contrib.auth.models import User
@csrf_exempt
def P_home(request):
context= locals()
template= 'P_home.html'
return render(request,template,context)
@csrf_exempt
def P_chat(request):
context= locals()
template= 'P_chat.html'
return render(request,template,context)
@csrf_exempt
def LogIIn(request):
if request.method == "POST":
name = request.POST.get('param1')
user = authenticate(username=name)
login(request, user)
return HttpResponse("OK")
@csrf_exempt
def Post(request):
if request.method == "POST":
msg = request.POST.get('param1')
if request.user.is_authenticated():
c = PChat(user=request.user, message=msg)
c.save()
return JsonResponse({ 'msg': msg, 'user': c.request.user })
else:
return HttpResponse("Account None")
models.py
from django.db import models
from django.db import models
from django.contrib.auth.models import User
class PChat(models.Model):
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User)
message = models.CharField(max_length=200)
def __unicode__(self):
return self.message
auth_backend.py
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class PasswordlessAuthBackend(ModelBackend):
"""Log in to Django without providing a password."""
def authenticate(self, username=None):
try:
return User.objects.get(username=username)
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
答案 0 :(得分:1)
你有问题:
c = PChat(user=request.user, message=msg)
request.user不是User对象。首先检查request.user是否为实际用户。
if request.user.is_authenticated():
c = PChat(user=request.user, message=msg)
c.save()
return JsonResponse({ 'msg': msg, 'user': c.user.username })
else:
return JsonResponse({ 'msg': 'user is not logged in' })
修改强>
def Post(request):
if request.method == "POST":
msg = request.POST.get('param1')
if request.user.is_authenticated():
c = PChat(user=request.user, message=msg)
c.save()
return JsonResponse({ 'msg': msg, 'user': c.request.user })
return HttpResponse("Account None")
答案 1 :(得分:1)
好的,您的代码有几处错误:
1)在 P_home 和 P_chat 中,您使用的是locals(),不建议这样做。你必须尽可能避免这种情况。您需要明确传递给 context 字典的数据。
2)在 LogIIn 视图中,当用户不是None时,您必须调用登录功能。 [1]
3)最终错误发生在发布视图中,您必须首先询问 request.user 是否已使用 request.user.is_authenticated()进行身份验证功能。如果用户已通过身份验证,那么 request.user 是正常的用户实例,在其他情况下,它将是 AnonymousUser ,它们都是不同的的东西。 PChat 模型中的字段用户期待用户而非 AnonymousUser 实例。
[1] https://docs.djangoproject.com/en/1.11/topics/auth/default/#how-to-log-a-user-in