无法在Django Web应用程序中添加评论表单

时间:2019-11-26 14:02:26

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

添加form-group时遇到麻烦(我相信这是引导程序类)。 表单组根本不执行任何操作,或者可能是form.authorform-body变量有问题!?

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

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,但效果不佳:enter image description here

我的评论部分:

enter image description here

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

我研究了该教程并实现了自己。答案在这里:

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)

修改

我更改了代码以支持从标题生成子弹字段。我没有处理异常,因此您将自己进行调查。祝你好运。