我有一个简单的聊天应用程序,我在其中自定义了身份验证后端以仅使用名称。到目前为止,它正在运行,并且用户已使用 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
最佳答案
好的,您的代码中有几个错误:
1) 在P_home和P_chat中,您正在使用locals(),不建议这样做。您必须尽可能避免这种情况。您需要明确传递给 context 字典的数据。
2) 在LogIIn View 中,当用户不是None时,您必须调用登录函数。 [1]
3) 最后的错误是在 Post View 中,您必须首先使用 request.user.is_authenticated() 询问 request.user 是否经过身份验证 功能。如果用户经过身份验证,则 request.user 是一个普通的 User 实例,否则它将是一个 AnonymousUser,它们都是不同的事物。 PChat 模型中的字段 user 需要 User 而不是 AnonymousUser 实例。
[1] https://docs.djangoproject.com/en/1.11/topics/auth/default/#how-to-log-a-user-in
关于python - 无法在 Django 中分配用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45663060/