无法在我的Django Web应用程序中添加普通的Comment部分

时间:2019-11-24 17:48:18

标签: django django-models django-forms django-templates django-views

我无法在django Web应用程序中添加评论。我想添加评论以允许用户评论帖子,就像在普通的网络博客中一样。我已经尝试了几种方法,但是对我而言,没有任何工作正常。

几周的搜索并尝试了不同的方法来解决此问题后,我就开始讨论这个问题了。我有一些进步,但现在完全是我想要的。

现在我只能在管理面板中添加“评论”

enter image description here

它看起来像这样(在管理面板中)

enter image description here

并以此方式(通过用户界面)

enter image description here

我对填充注释有这个问题(我不太明白为什么会发生¯_(ツ)_ /¯

无论如何,这是我的代码,希望有人知道如何解决此问题:

models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.TextField()
    created_date = models.DateField(auto_now_add=True)

    def __str__(self):
        return self.text

...

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    categories = models.ManyToManyField('Category', related_name='posts')
    image = models.ImageField(upload_to='images/', default="images/None/no-img.jpg")
    slug= models.SlugField(max_length=500, unique=True, null=True, blank=True)


    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'slug': self.slug})

post_detail.html

<article class="media content-section">
  {% for comment in post.comments.all %}
   <ul>
    {{ comment.text }}
    {% for reply in comment.replies.all %}
        <li>
            {{ reply.text }}
        </li>
    {% endfor %}
   <ul>
   {% endfor %}
</article>

我还阅读了this article的有关初学者创建博客的信息,他们有我想要的工作注释部分,但我尝试将其代码实现到我的Web应用程序中,但对我没有任何帮助。

他们有这样的评论部分(我需要完全一样): enter image description here

但是当我尝试遵循他们的教程时,我只有这样:

enter image description here

这是此失败的解决方案的代码(但我觉得它正在工作,也许我做错了事)

post_detail.html

{% extends 'blog/base.html' %}
{% block content %}
  <article class="media content-section">
    <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}" alt="">
    <div class="article-metadata">
      <a class="mr-2 author_title" href="{% url 'user-posts' object.author.username %}">@{{ object.author }}</a>
      <small class="text-muted">{{ object.date_posted|date:"N d, Y" }}</small>

      <div>
        <!-- category section -->
        <small class="text-muted">
          Categories:&nbsp;
          {% for category in post.categories.all %}
          <a href="{% url 'blog_category' category.name %}">
            {{ category.name }}
          </a>&nbsp;
          {% endfor %}
        </small>
      </div>

      {% if object.author == user %}
        <div>
          <a class='btn btn-secondary btn-sm mt-1 mb-1' href="{% url 'post-update' object.slug %}">Update</a>
          <a class='btn btn-danger btn-sm mt-1 mb-1' href="{% url 'post-delete' object.slug %}">Delete</a>
        </div>
      {% endif %}
    </div>
  </article>
  <article class="media content-section">
    <div class="media-body">
      <img class="img-fluid center" id="rcorners3" src="{{ object.image.url }}" alt="none">
      <h2 class="article-title text-center">{{ object.title }}</h2>
      <p class="article-content">{{ object.content }}</p>
    </div>
  </article>
<article class="media content-section">
  <form action="/blog/{{ post.pk }}/" method="post">

       {% csrf_token %}

       <div class="form-group">

           {{ form.author }}

       </div>

       <div class="form-group">

           {{ form.body }}

       </div>

       <button type="submit" class="btn btn-primary">Submit</button>

   </form>

   <h3>Comments:</h3>

   {% for comment in comments %}

   <p>

       On {{comment.created_on.date }}&nbsp;

       <b>{{ comment.author }}</b> wrote:

   </p>

   <p>{{ comment.body }}</p>

   <hr>

   {% endfor %}
</article>
{% endblock content %}

views.py

...
def comment(request):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post
            )
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form,
    }

models.py

...
class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.TextField()
    created_date = models.DateField(auto_now_add=True)

    def __str__(self):
        return self.text

forms.py

from django import forms

class CommentForm(forms.Form):
    author = forms.CharField(
        max_length=60,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": "Your Name"
        })
    )
    body = forms.CharField(widget=forms.Textarea(
        attrs={
            "class": "form-control",
            "placeholder": "Leave a comment!"
        })
    )

1 个答案:

答案 0 :(得分:0)

您正在创建不必要的列表。试试这个

<article class="media content-section">

   <ul>
   {% for comment in post.comments.all %}
    <li>{{ comment.text }}</li>
    {% if comment.replies.all %}
    <ul>
      {% for reply in comment.replies.all %}
        <li>{{ reply.text }}</li>
      {% endfor %}
     </ul>
     {% endif %}
    {% endfor %}
   <ul>

</article>