AttributeError:“AnonymousUser”对象没有属性“\u meta”Django通道

2024-09-27 00:11:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试登录django频道的用户及其抛出

AttributeError: 'AnonymousUser' object has no attribute '_meta'

我的消费者

class LoginConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.room_name = "login_room"
        self.room_group_name = "login_group"
        await self.channel_layer.group_add(self.room_group_name, self.channel_name)
        await self.accept()
        await self.send(json.dumps({"message": "connected to login socket"}))

    async def receive(self, text_data):
        self.json_data = json.loads(text_data)

        await login(self.scope, await self.query())
        await database_sync_to_async(self.scope["session"].save)()

    async def query(self):
        await self.get_user_from_db()

    @database_sync_to_async
    def get_user_from_db(self):
        user = User.objects.get(username=self.json_data["username"])
        return user

    async def disconnect(self, code):
        print("disconnected")
        await super().disconnect(code)

我的登录视图

def login_user(request):
    if request.user.is_anonymous:
        if request.method == "POST":
            username = request.POST.get("username")
            password = request.POST.get("password")
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect("index")
            else:
                messages.error(request, "invalid username or password")
                return redirect("login")
        return render(request, "login.html")
    else:
        return redirect("index")

我的js文件

const username = document.querySelector(".username");
const password = document.querySelector(".password");
const socket = new WebSocket("ws://localhost:8000/ws/auth/login");
const button = document.querySelector("button");
button.addEventListener("click", (e) => {
  if (password.value !== "" && username.value !== "") {
    socket.send(
      JSON.stringify({
        username: username.value,
        password: password.value,
      })
    );
  }
});

完全回溯:

Exception inside application: 'AnonymousUser' object has no attribute '_meta'
Traceback (most recent call last):
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__
    return await self.application(scope, receive, send)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__
    return await application(scope, receive, send)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/sessions.py", line 47, in __call__
    return await self.inner(dict(scope, cookies=cookies), receive, send)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/sessions.py", line 263, in __call__
    return await self.inner(wrapper.scope, receive, wrapper.send)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/auth.py", line 185, in __call__
    return await super().__call__(scope, receive, send)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/middleware.py", line 26, in __call__
    return await self.inner(scope, receive, send)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/routing.py", line 150, in __call__
    return await application(
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/consumer.py", line 94, in app
    return await consumer(scope, receive, send)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/consumer.py", line 58, in __call__
    await await_many_dispatch(
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/utils.py", line 51, in await_many_dispatch
    await dispatch(result)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/consumer.py", line 73, in dispatch
    await handler(message)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/generic/websocket.py", line 194, in websocket_receive
    await self.receive(text_data=message["text"])
  File "/home/__neeraj__/Documents/chat/auth_user/consumers.py", line 20, in receive
    await login(self.scope, await self.query())
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/asgiref/sync.py", line 444, in __call__
    ret = await asyncio.wait_for(future, timeout=None)
  File "/usr/lib/python3.9/asyncio/tasks.py", line 442, in wait_for
    return await fut
  File "/usr/lib/python3.9/concurrent/futures/thread.py", line 52, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/db.py", line 13, in thread_handler
    return super().thread_handler(loop, *args, **kwargs)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/asgiref/sync.py", line 486, in thread_handler
    return func(*args, **kwargs)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/auth.py", line 106, in login
    session[SESSION_KEY] = user._meta.pk.value_to_string(user)
  File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/utils/functional.py", line 247, in inner
    return func(self._wrapped, *args)
AttributeError: 'AnonymousUser' object has no attribute '_meta'

此错误发生在使用者而不是视图上


Tags: inpyselfhomereturnlibpackageslocal

热门问题