简体   繁体   English

Django - 为不同的页面创建一个评论系统,使用一个评论 model

[英]Django - Creating a comment system for different pages, using one Comment model

I'm trying to create a website with a page for information about different cities.我正在尝试创建一个网站,其中包含有关不同城市的信息的页面。 At the bottom of each page, I want there to be a comment section.在每一页的底部,我希望有一个评论部分。 My idea is to have a Comment model, which stores all the comments in one place, with each comment object having a field called 'page' which tells me the page they should be displayed on.我的想法是有一个评论 model,它将所有评论存储在一个地方,每个评论 object 都有一个名为“页面”的字段,它告诉我它们应该显示在哪个页面上。 Then I can just filter through the comments so only the ones for the right page are displayed.然后我可以过滤评论,以便只显示正确页面的评论。

So far I have created a City model which is used by a detail view, CityDetailView, to create a page for each of the cities.到目前为止,我已经创建了一个 City model,详细视图 CityDetailView 使用它来为每个城市创建一个页面。 This works well and uses a slug for the URLs.这很好用,并为 URL 使用 slug。 I've made a Comment model which accepts: 'content' (describing the city), 'date_posted', 'author' and 'page' which I've connected to the City model through a foreign key.我发表了评论 model 接受:“内容”(描述城市)、“发布日期”、“作者”和“页面”,我已通过外键连接到城市 model。 It's my thinking that this 'page' field can be used to store what page the comment was written on, so that I can use {{ if comments.page == cites.name}} or something in my city.html template to display the comments only to the correct page.我认为这个“页面”字段可用于存储评论写在哪个页面上,以便我可以使用{{ if comments.page == cites.name}}或我的 city.html 模板中的内容来显示仅对正确页面的评论。

Going with this thinking, I'm guessing I would need to make a ListView inside the CityDetailView to list the comments.带着这种想法,我猜我需要在 CityDetailView 中创建一个 ListView 来列出评论。 Is this right?这是正确的吗? I feel there is a better way to do this so any help would be greatly appreciated.我觉得有更好的方法可以做到这一点,所以任何帮助都将不胜感激。

Here is the relevent code, at the moment, no comments show up for the city pages.这是相关代码,目前,城市页面没有评论。 I have added these manually through the shell, one for each of the two test pages.我已经通过 shell 手动添加了这些,两个测试页各一个。

views.py视图.py

from django.shortcuts import render
from django.views.generic import DetailView, ListView
from .models import Post, Comment, City, County


def home(request):
    return render(request, 'blog/home.html', {'title':'TIP Home'})   


class CityDetailView(DetailView):
    model = City
    template_name = 'blog/city.html'
    context_object_name = 'cities'

    class CommentsView(ListView):
        model = Comment
        context_object_name = 'comments'

urls.py网址.py

from django.urls import path
from . import views 
from .views import CityDetailView, CountyDetailView

urlpatterns = [
    path('', views.home, name='blog-home'),
    path('<slug>/', CityDetailView.as_view(), name='city-detail'),
]

models.py模型.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models.signals import pre_save
from django.utils.text import slugify

class City(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=250, null=True, blank=True)
    about = models.TextField()

    def __str__(self):
        return self.title

class Comment(models.Model):
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    page = models.ForeignKey(City, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.author)+'-'+str(self.page)+'-'+str(self.pk)        


def slug_generator(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = slugify(instance.title)

pre_save.connect(slug_generator, sender=City)

city.html city.html

{% extends "blog/base.html" %}
{% load static %}
{% block content %}
    <div class="page_heading"><h1>{{ cities.title }}</h1></div>
    <p><center>{{ cities.about }}</center></p>


    {% for comment in comments %}

            <article class="media content-section">
              <div class="media-body">
                <div class="article-metadata">
                  <a class="mr-2" href="#">{{ comment.author }}</a>
                  <small class="text-muted">{{ comment.date_posted|date:'Y n d'  }}</small>
                </div>
                <p class="article-content">{{ comment.content }}</p>
              </div>
            </article>

    {% endfor%}


{% endblock content %}

Override the get_context_data and through there get access to all the comments for the appropriate page slug.覆盖 get_context_data 并通过那里访问相应页面 slug 的所有评论。

class CityDetailView(DetailView):
    model = City
    template_name = 'blog/city.html'
    context_object_name = 'cities'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = Comment.objects.get(page_slug=self.kwargs['slug'])

        return context

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM