我有一個簡單的聊天應用程序,我在其中自定義身份驗證後端以僅使用名稱。到目前爲止,它正在工作,用戶使用Django login()登錄。無法在Django中分配用戶
現在我有一個分配給用戶一個問題,即這個錯誤過來了,CUS應用程序的其它部分停止:
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
感謝大家的反饋,我已經試過您的解決方案通過我得到這個錯誤' ValueError異常:視圖Pchat.Pviews.Post沒有返回HttpResponse對象。它返回None而不是。' – Eman
你可以在上述問題中更新你的代碼嗎? –
我更新了Pview.py中的代碼 – Eman