【问题标题】:How to access pk in views (Django)如何在视图中访问 pk (Django)
【发布时间】: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


【解决方案1】:

您应该定义get_queryset 方法而不是独立的queryset 属性。

def get_queryset(self, *args, **kwargs):
    return Comment.objects.filter(chat_id=self.kwargs['pk'])

【讨论】:

  • 效果很好,谢谢。在我的 .html 中,还有一种方法可以处理模型中的聊天变量 -> 聊天名称、描述、created_at。它起作用的唯一方法是当我使用“上下文”时,但那是没有 ListView
  • 您需要定义 get_context_data 以返回包含您的 Chat 对象的字典。
【解决方案2】:

您可以使用普通视图代替CommentList

def comments_index(request, chatid):
    return render(request, 'xxx/comment_list.html', {
        'comments': Comment.objects.filter(chat_id=chatid)
    })

在网址中:

url(r'^comments/(?P<chatid>[0-9]+)/$', views.comments_index, name='comments'),

【讨论】:

    猜你喜欢
    • 2019-08-26
    • 2021-04-27
    • 1970-01-01
    • 2020-09-30
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    相关资源
    最近更新 更多