【问题标题】:Can't add comment form in Django web application无法在 Django Web 应用程序中添加评论表单
【发布时间】:2020-03-21 23:22:59
【问题描述】:

我无法添加form-group(我相信它是引导类)。 表单组根本没有做任何事情,或者可能是form.authorform-body 变量的问题!?

更简单地说,我需要 UI 评论部分(现在只有我可以从 django 管理页面添加和编辑 cmets)。一些代码:

post_details.html

<article class="media content-section">

      <form action="/post/{{ post.slug }}/" 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>

       <ul>
       {% for comment in post.comments.all %}
        <p>
          <b>@{{ comment.author }}</b>
          <small>{{ comment.created_date }} </small>
        </p>
        <p>    {{ comment.text }}</p>
        <hr>
        {% if comment.replies.all %}
        <ul>
          {% for reply in comment.replies.all %}
            <p>{{ reply.text }}</p>
            <hr>
          {% endfor %}
         </ul>
         {% endif %}
        {% endfor %}
       <ul>

    </article>

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!"}
        )
    )

views.py

def comment(request):

    form = CommentForm()
    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()

    context = {"post": post, "comments": comments, "form": form}

    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

编辑:

urls.py

from django.urls import path
from django.conf.urls import include, url
from . import views
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView

urlpatterns = [
    #Blog section
    path("", PostListView.as_view(), name='blog-home'),
    path("user/<str:username>", UserPostListView.as_view(), name='user-posts'),
    path('post/<slug:slug>/', PostDetailView.as_view(), name='post-detail'),
    path("posts/new/", PostCreateView.as_view(), name='post-create'),
    path("post/<slug:slug>/update/", PostUpdateView.as_view(), name='post-update'),
    path("post/<slug:slug>/delete/", PostDeleteView.as_view(), name='post-delete'),
    path("about/", views.about, name="blog-about"),
    path("<category>/", views.blog_category, name="blog_category"),
]

我真的需要这样的东西(尝试关注this tutorial,但没有任何效果:

我的评论区:

【问题讨论】:

  • 你能提供你的urls.py吗?
  • 添加了 urls.py。见编辑
  • 嗨,您是否添加了 Stéphane 指出的 return 语句?
  • @EliakinCosta 我认为问题不在于回报,问题在于我没有允许用户输入评论信息的表格(作者和正文),但是,正如我所提到的,我可以在 django 管理页面中添加 cmets。请看教程,也许我丢失了一些东西:realpython.com/get-started-with-django-1/…
  • 当然,这也是一个问题。您的观点不正确,因为您没有指向 view.comment。 @C O D E

标签: django django-models bootstrap-4 django-forms django-templates


【解决方案1】:

我已经研究了该教程并自己实现了。答案如下:

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path("", views.blog_index, name="blog_index"),
    path("<slug:slug>/", views.post_detail, name="post_detail"),
    path("<category>/", views.blog_category, name="blog_category"),
]

models.py

from django.db import models
from django.utils.text import slugify

class Category(models.Model):
    name = models.CharField(max_length=20)


class Post(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    categories = models.ManyToManyField("Category", related_name="posts")
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)


class Comment(models.Model):
    author = models.CharField(max_length=60)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey("Post", on_delete=models.CASCADE)

post_detail.html

{% extends "blog_app/base.html" %}
{% block page_content %}
<div class="col-md-8 offset-md-2">
    <h1>{{ post.title }}</h1>
    <small>
        {{ post.created_on.date }} |&nbsp;
        Categories:&nbsp;
        {% for category in post.categories.all %}
        <a href="{% url 'blog_category' category.name %}">
            {{ category.name }}
        </a>&nbsp;
        {% endfor %}
    </small>
    <p>{{ post.body | linebreaks }}</p>
    <h3>Leave a comment:</h3>
    <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 %}
</div>
{% endblock %}

views.py

def post_detail(request, slug):
    post = Post.objects.get(slug=slug)
    comments = Comment.objects.filter(post=post)

    form = CommentForm()
    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()

    context = {"post": post, "comments": comments, "form": form}
    return render(request, "blog_app/post_detail.html", context)

编辑

我已更改代码以支持从标题生成 slug 字段。我不处理异常,因此您将自己研究它。祝你好运。

【讨论】:

    【解决方案2】:

    我认为问题在于您使用的是 Form 而不是 ModelForm。

    class CommentForm(forms.ModelForm):
        class Meta:
            model = Comment
            fields = ['author', 'text']
        ...
    

    【讨论】:

    • 对我不起作用。我按照教程(realpython.com/get-started-with-django-1/…)进行操作;请看一下,也许我丢了一些东西。我他们的教程一切正常。我的问题 - 我没有从 UI 输入 cmets 的表单,但我可以在管理页面中完成(添加屏幕截图;见编辑)
    【解决方案3】:

    在您的文件 views.py 中,您有重复的代码并且没有返回 声明:

    return render(request, "post_details.html", context)
    

    【讨论】:

    • 这也是个问题,但他们没有将comment 视图函数连接到 URL。我怀疑问题是PostDetailView 不包括评论表单。
    猜你喜欢
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多