【发布时间】:2017-04-19 14:53:14
【问题描述】:
我正在用 Django 编写一个小型聊天程序,但在继续前进时遇到了问题。
代码如下:
models.py
from django.db import models
from datetime import datetime
from django.utils import timezone
class Chat(models.Model):
chatname = models.CharField(max_length=100)
description = models.TextField()
created_at = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.chatname
class Comment(models.Model):
chat = models.ForeignKey(Chat, on_delete=models.CASCADE)
commenter = models.CharField(max_length=30)
comment = models.TextField()
created_at = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.comment
urls.py
from django.conf.urls import url
from . import views
from django.views.generic import ListView
from chat.views import CommentList
app_name = 'chats'
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^comments/(?P<pk>[0-9]+)/$', views.CommentList.as_view(), name='comments'),
]
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
from django.views import generic
from .models import Chat, Comment
def index(request):
username = None
if request.user.is_authenticated():
username = request.user.username
chats = Chat.objects.all()[:10]
context = {
'chats':chats
}
return render(request, 'chat/index.html', context)
class CommentList(generic.ListView):
queryset = Comment.objects.filter(chat_id=1)
context_object_name = 'comments'
我的comment_list.html
{% extends "chat/base.html" %}
{% block content %}
<a href="/chat/">Go back</a>
<h3>Comments</h3>
<h2>{{chat.id}}</h2>
<ul>
{% for comment in comments %}
<li>{{ comment.commenter }}: {{ comment.comment }}</li>
{% endfor %}
</ul>
{% endblock %}
我的数据库结构包含这两个模型:聊天和评论。每个聊天室(房间)都应该有自己的 cmets。我使用“models.ForeignKey”来过滤每个聊天室(房间)的 cmets。在我的 index.html 中,我列出了所有的聊天,每个聊天都有一个指向 /cmets/ 部分的超链接。
在我的views.py中我有这一行:'queryset = Comment.objects.filter(chat_id=1)' Chat_id 是 cmets sql 表中的列,现在它只会显示属于 pk=1 的聊天的 cmets。如何自动访问不同网址的聊天 /cmets/1/ /cmets/2/ 等等..?
希望解释清楚。对不起初学者,如果没有多大意义,我可以尝试进一步解释。
最好, 费边
【问题讨论】:
-
另一个(连贯的)问题是comment_list.html 中的
{{chat.id}}
未显示在网站上。我不太确定如何“链接” cmets 和聊天,所以我可以在我的 html 代码中访问两者
标签: python django views display