简体   繁体   English

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

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

I am trying to create a comment creation page related to a single post on a blog-style site using Django.我正在尝试使用 Django 在博客风格网站上创建与单个帖子相关的评论创建页面。

The home page has a list of posts, each with a "comment" button.主页有一个帖子列表,每个帖子都有一个“评论”按钮。 Ideally this "comment" button would then take you to a page that would have the original post listed at the top with the comment creation form underneath it.理想情况下,这个“评论”按钮会将您带到一个页面,该页面的顶部列出了原始帖子,下方是评论创建表单。

I've been trying to figure out a way to access the data I'm looking for using primary keys but am not sure how to tie everything together.我一直在尝试找出一种方法来使用主键访问我正在寻找的数据,但不确定如何将所有内容联系在一起。

Here are the 2 models I am trying to access ( Post and Comment ):以下是我尝试访问的 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)

And the urls.py :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'),
]

This is my current HTML for the home page (currently adds the post id to the end of the HTML on linked "comment-create" page):这是我当前的 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>

This is my current HTML for the comment-creation page:这是我当前的 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 %}

Here is the view for comment creation page (using get_context_data to access the Post model):这是评论创建页面的视图(使用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)

Currently, I can't access any of the data for the post in the comment creation page.目前,我无法访问评论创建页面中帖子的任何数据。 I think it has to do with how I'm trying to tie the pk to the post within the -get_context_data` function.我认为这与我如何尝试将pk与 -get_context_data` function 中的post联系起来有关。 The primary key for the desired post is showing up in the URL, just not sure how to get at the right data.所需帖子的主键显示在 URL 中,只是不确定如何获取正确的数据。

Any help would be much appreciated.任何帮助将非常感激。 Thank you!谢谢!

So it looks to me like you're using pk wrong here.所以在我看来你在这里使用pk是错误的。

The pk in this code segment here:此代码段中的pk在这里:

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

is the pk of the comment , however you're trying to use it to lookup a Post with context['post'] = Post.objects.filter(id=pk) .commentpk ,但是您尝试使用它来查找带有 context[' Post context['post'] = Post.objects.filter(id=pk) Remember that pk stands for primary key and references the object that you declared as the model for your view.请记住, pk代表primary key并引用您声明为 model 的model以供您查看。 If you want the Post associated with that Comment you'll need to search for it using Comment.post since that's the declared foreign key inside your model.如果您想要与该Comment关联的Post ,您需要使用Comment.post搜索它,因为这是 model 中声明的外键。

After a lot of Googling/trial-and-error, I found a solution that got me what I was looking for.经过大量的谷歌搜索/反复试验,我找到了一个解决方案,让我得到了我想要的东西。

Updated my View from THIS (note: I was trying to force a specific PK to test if it would filter to the correct data, but for some reason I still couldn't access anything):从这个更新了我的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)

To THIS:对此:

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)

Have a basic, high-level understanding of what this is doing (grabbing the PK from the URL), but am not entirely sure why the original .filter() method wasn't working.对它的作用有一个基本的、高级的理解(从 URL 中获取PK ),但我不完全确定为什么原来的.filter()方法不起作用。

If anyone could provide some context as to what's going on behind the scenes here, I'd love to see it.如果有人可以提供一些关于这里幕后发生的事情的背景信息,我很乐意看到它。

Thanks!谢谢!

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

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