#python #django #django-channels
Вопрос:
Я пытаюсь войти в систему пользователей в каналах 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 !== "" amp;amp; 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'
Эта ошибка возникает у потребителя, а не у представления