繁体   English   中英

如何在 Django 中创建与单个博客样式帖子相关的评论创建页面

[英]How to create a comment-creation page related to a single blog-style post in Django

我正在尝试使用 Django 在博客风格网站上创建与单个帖子相关的评论创建页面。

主页有一个帖子列表,每个帖子都有一个“评论”按钮。 理想情况下,这个“评论”按钮会将您带到一个页面,该页面的顶部列出了原始帖子,下方是评论创建表单。

我一直在尝试找出一种方法来使用主键访问我正在寻找的数据,但不确定如何将所有内容联系在一起。

以下是我尝试访问的 2 个模型( PostComment ):

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    title = models.CharField(max_length=128)
    content = models.TextField()
    image = models.ImageField(upload_to='post_pics', blank=True)
    date_posted = models.DateTimeField(default=timezone.now)

    def get_absolute_url(self):
        return reverse('home')

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    comment = models.TextField()
    date_created = models.DateTimeField(default=timezone.now)

urls.py

from django.urls import path
from .views import PostCreateView, PostListView, VehicleListView, CommentCreateView
from . import views

urlpatterns = [
    path('', PostListView.as_view(), name='home'),
    path('comment/new/<int:pk>', CommentCreateView.as_view(), name='comment-create'),
]

这是我当前的 HTML 主页(当前在链接的“评论创建”页面上将帖子 ID 添加到 HTML 的末尾):

{% for post in posts %}
    <div class="infinite-item">
      <div class="card m-3">
        <div class="card-body" style="background-color:#bdcade; padding-bottom:0px">
          <div class="media mb-3">
            <img src="{{ user.profile.image.url }}" class="d-block ui-w-40 rounded-circle" style="width:40px;height:auto;" alt="">
            <div class="media-body ml-3">
              <h5 style="color:#ffffff">{{ post.user.username }}</h5>
              <div class="small text-muted">Yesterday</div>
            </div>
          </div>
        </div>

        <div class="card-body">
          <h5 class="card-title">{{ post.title }}</h5>
          <p class="card-text">{{ post.content }}</p>
          <div class="btn-group" role="group">
            <button type="button" class="btn btn-secondary">Like</button>
            <a class="btn btn-secondary" href="{% url 'comment-create' post.id %}" role="button">Comment</a>

          </div>
        </div>
      </div>
    </div>

这是我当前的 HTML 用于评论创建页面:

{% block content %}

  <div class="card m-3">
    <div class="card-body" style="background-color:#bdcade; padding-bottom:0px">
      <div class="media mb-3">
        <img src="{{ post.user.profile.image.url }}" class="d-block ui-w-40 rounded-circle" style="width:40px;height:auto;" alt="">
        <div class="media-body ml-3">
          <h5 style="color:#ffffff">{{ post.user.username }}</h5>
          <div class="small text-muted">{{ post.title }}</div>
        </div>
      </div>
    </div>

    <div class="card-body">
      <h5 class="card-title">{{ post.title }}</h5>
      <p class="card-text">{{ post.content }}</p>
      <div class="btn-group" role="group">
        <button type="button" class="btn btn-secondary">Like</button>
        <button type="button" class="btn btn-secondary">Comment</button>
      </div>
    </div>
  </div>

  <br>
  <div class="container primary-segments">
    <form method="POST" enctype="multipart/form-data">
      {% csrf_token %}
      <fieldset>
        {{ form|crispy }}
      </fieldset>
      <div class="form-group">
        <button class="btn btn-outline-info" type="submit">Post Comment</button>
      </div>
    </form>
  </div>

{% endblock content %}

这是评论创建页面的视图(使用get_context_data访问Post模型):

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    template_name = 'home/comment-form.html'
    fields = ['comment',]

    def get_context_data(self, **kwargs):
        context = super(CommentCreateView, self).get_context_data(**kwargs)
        pk = self.kwargs['pk']
        context['post'] = Post.objects.filter(id=pk)
        return context

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

目前,我无法访问评论创建页面中帖子的任何数据。 我认为这与我如何尝试将pk与 -get_context_data` function 中的post联系起来有关。 所需帖子的主键显示在 URL 中,只是不确定如何获取正确的数据。

任何帮助将非常感激。 谢谢!

所以在我看来你在这里使用pk是错误的。

此代码段中的pk在这里:

def get_context_data(self, **kwargs):
        context = super(CommentCreateView, self).get_context_data(**kwargs)
        pk = self.kwargs['pk']

commentpk ,但是您尝试使用它来查找带有 context[' Post context['post'] = Post.objects.filter(id=pk) 请记住, pk代表primary key并引用您声明为 model 的model以供您查看。 如果您想要与该Comment关联的Post ,您需要使用Comment.post搜索它,因为这是 model 中声明的外键。

经过大量的谷歌搜索/反复试验,我找到了一个解决方案,让我得到了我想要的东西。

从这个更新了我的View (注意:我试图强制一个特定的PK来测试它是否会过滤到正确的数据,但由于某种原因我仍然无法访问任何东西):

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    template_name = 'home/comment-form.html'
    fields = ['comment',]

    def get_context_data(self, **kwargs):
        context = super(CommentCreateView, self).get_context_data(**kwargs)
        pk = 7
        context['post'] = Post.objects.filter(id=pk)
        return context

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

对此:

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    template_name = 'home/comment-form.html'
    fields = ['comment',]

    def get_context_data(self, **kwargs):
        context = super(CommentCreateView, self).get_context_data(**kwargs)
        context['post'] = Post.objects.get(pk=self.kwargs['pk'])
        return context

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

对它的作用有一个基本的、高级的理解(从 URL 中获取PK ),但我不完全确定为什么原来的.filter()方法不起作用。

如果有人可以提供一些关于这里幕后发生的事情的背景信息,我很乐意看到它。

谢谢!

暂无
暂无

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

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