1

我正在尝试在 Django 中创建聊天室。我使用 Redis 服务器和 Django 频道。我也有模型 Project 和 Room。每个项目都有自己的聊天室。当我尝试通过下面的这个 url 打开聊天室页面时出现错误。在我看来,我的 consumer.py 文件不正确。如何修复此错误。需要帮忙!

网址

url(r'^(?P<project_code>[0-9a-f-]+)/chat_room/$', chat_room, name='chat_room'),

错误

[2017/03/22 12:44:42] WebSocket HANDSHAKING /chat/ru/account/dashboard/projects/1744d0bc-e439-4562-9c29-4e7b2451f39c/chat_room/ [127.0.0.1:63104]
2017-03-22 12:44:42,236 - ERROR - worker - Error processing message with consumer project.consumers.ws_connect:
Traceback (most recent call last):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\worker.py", line 119, in run
    consumer(message, **kwargs)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\sessions.py", line 78, in inner
    return func(*args, **kwargs)
File "C:\Users\Nurzhan\PycharmProjects\RMS\project\consumers.py", line 27, in ws_disconnect
    project_code = message.channel_session['room']
TypeError: ws_connect() missing 1 required positional argument: 'project_code'
[2017/03/22 12:44:47] WebSocket DISCONNECT /chat/ru/account/dashboard/projects/1744d0bc-e439-4562-9c29-4e7b2451f39c/chat_room/ [127.0.0.1:63104]

模型.py

class Room(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False)

    def __str__(self):
        return self.code

    def get_absolute_url(self):
        return reverse('project:chat_room', args=[self.project_code])


class Message(models.Model):
    room = models.ForeignKey(Room, related_name='messages')
    handle = models.TextField()
    message = models.TextField()
    timestamp = models.DateTimeField(default=timezone.now, db_index=True)

    def __unicode__(self):
        return '[{timestamp}] {handle}: {message}'.format(**self.as_dict())

    def __str__(self):
        return self.__unicode__()

    @property
    def formatted_timestamp(self):
        return self.timestamp.strftime('%b %-d %-I:%M %p')

    def as_dict(self):
        return {'handle': self.handle, 'message': self.message, 'timestamp': self.formatted_timestamp}

视图.py

@login_required
def chat_room(request, project_code):
    # If the room with the given project_code doesn't exist, automatically create it upon first visit.
    room, created = Room.objects.get_or_create(project=project_code)
    # We want to show the last 50 messages, ordered most-recent-last
    messages = reversed(room.messages.order_by('-timestamp')[:50])
    return render(request, "project/chat/room.html", {'room': room, 'messages': messages,})

消费者.py

@channel_session
def ws_connect(message, project_code):
    room = Room.objects.get(project_id=project_code)
    message.reply_channel.send({"accept": True})
    Group('chat-' + project_code).add(message.reply_channel)
    message.channel_session['room'] = room.project


@channel_session
def ws_receive(message):
    project_code = message.channel_session['room']
    room = Room.objects.get(project_id=project_code)
    data = json.loads(message['text'])
    m = room.messages.create(handle=data['handle'], message=data['message'])
    Group('chat-' + project_code).send({'text': json.dumps(m.as_dict())})


@channel_session
def ws_disconnect(message):
    project_code = message.channel_session['room']
    Group('chat-' + project_code).discard(message.reply_channel)
4

2 回答 2

2

我觉得你正在传递id给模型。尝试

room = Room(project_id=project_code)
于 2017-03-22T05:41:44.180 回答
2
room, created = Room.objects.get_or_create(project_code=project_code)

使用您在模型类project_code中提到的您自己的属性。Project

于 2017-03-22T05:24:52.993 回答