简体   繁体   中英

Cannot assign a user in Django

i have a simple chat application where i've customize the Authentication back end to use only the name. So far it is working and the users is logged in using Django login().

Now i have a problem with assign a user where this Error came up and cus the rest of the app to stop:

    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     

You have problem in line:

c = PChat(user=request.user, message=msg)

request.user is not a User object. Firstly check request.user is actual user or not.

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' })

Edit

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")

OK, there are several errors on your code:

1) In P_home and P_chat you are using locals(), that's not recommended. You must avoid that whenever possible. You need to be explicit with data passed to the context dictionary.

2) In LogIIn view you must call login function when user is not None. [1]

3) The final error is in Post view, you must ask first wheter request.user is authenticated or not using request.user.is_authenticated() function. If the user is authenticated, then request.user is a normal User instance in other case its going to be an AnonymousUser , they both are different things. The field user in PChat model is expecting an User instead an AnonymousUser instance.

[1] https://docs.djangoproject.com/en/1.11/topics/auth/default/#how-to-log-a-user-in

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM