簡體   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