Django-无法访问DetailView模型对象的值

时间:2018-02-01 22:21:58

标签: python django

我正在尝试创建一个包含两个模型的聊天应用程序:一个持有聊天室名称,另一个持有消息。

billing_address[country_id]

但是,每当我尝试从模板访问这些字段时,都会收到以下错误:

  

聊天中找不到与查询匹配的消息

在尝试此操作之前,我确实用虚拟值填充模型。

以下是我使用的views.py文件和模板:

views.py

from django.db import models

class ChatRoom(models.Model):
    name = models.CharField(max_length=256)
    professor = models.CharField(max_length=256)
    def __str__(self):
        return self.name


    class MessagesInChat(models.Model):
        room_name = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, related_name="message_room")
            user_name = models.CharField(max_length=256)
            message = models.TextField(blank=True, null=True)

        def __str__(self):
            return str(self.user_name)

模板

from django.views.generic import DetailView, ListView
from chat import models

class Chats(ListView):
    template_name = "chat_list.html"
    context_object_name = "chat_list"
    model = models.ChatRoom

    def get_queryset(self):
        return models.ChatRoom.objects.order_by("name")


class ChatPage(DetailView):
    model = models.MessagesInChat
    template_name = "chat.html"
    context_object_name = "chat_page"

urls.py文件:

<!-- 'm' stands for message --> 
    {%for m in chat_page.message_room.all%}
      <div class="p-3 mb-2 bg-light text-dark" style="margin-top:20px;">{{m.message}}</div>
      <div class="p-3 mb-2 bg-success text-white" style="margin-top:20px;">{{m.message}}</div>
    {%endfor%}

这个问题一直困扰着我。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果网址中的pkChatRoom个实例的主键,那么您应该在视图中使用model = models.ChatRoom

class ChatPage(DetailView):
    model = models.ChatRoom
    template_name = "chat.html"
    context_object_name = "chat_page"