我在Django的模板上渲染我的评论表单时遇到问题

时间:2017-09-05 10:17:21

标签: django django-forms django-class-based-views

大家好,我一直在尝试使用Django在我的博客项目中集成一个简单的评论表单,但表单从未显示在我的模板上。请看看我的代码并告诉我什么是错的 我需要知道如何组合Detail视图和FormView,以便我可以在同一模板上进行渲染

评论表格(forms.py)

from django import forms
from .models import Comment


class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('comment',)

VIEWS.PY

    from django.views.generic import (ListView, DetailView,FormView)
    from .import models
    from django.shortcuts import render
    from django.template import RequestContext
    from .forms import CommentForm

    class EntryDetail(DetailView):
        model = models.EntryPost
        form_class = CommentForm
        template_name = "post.html"

        def comment_valid(request, form):
            if request.method == "POST":
                comment_form = form_class(request.POST or None)
                if comment_form.is_valid():
                    comment = comment_form.cleaned_data['comment']
                    comment.save()
                    return super(EntryDetail).comment_valid(form)
                else:
                    form = CommentForm()
                return render(request,'post.html',{"form":comment_form,})

FORM TEMPLATE

{% extends "base.html" %}
{# {% load django_markdown %} #}

{% block entry_posts %}
  <div class="post">
    <h2><a href="{% url "entry" slug=object.slug %}">{{ object.title }}</a></h2>
    <p class="meta">
      {{ object.created }} |
      Tagged under {{  object.tags.all|join:", " }}
    </p>
    {{ object.body }}
  </div>

  <form method="POST" action="">{% csrf_token %} 
    {{form}}

  <input type="submit" value="Post Comment" class="btn btn-default">
  </form>

  <div class="post">

    <strong>COMMENTS</strong> 
    <hr/>
    {% for comment in entrypost.comments.all %}
    {% if comment.approve %}
    <div class="comment">
      <strong>{{ comment.name}}| created:{{comment.created}}</strong>
      <p>{{comment.comment|linebreaks}}</p>
    </div>
    {% endif %}
    {% empty %}
    <p> no comments :)</p>

    {% endfor %}

  </div>



{% endblock %}

请告诉我错误的原因当我运行服务器时我无法看到评论字段输入评论我只能看到帖子评论按钮。我非常欢迎有助于解决这个问题的贡献

1 个答案:

答案 0 :(得分:0)

您在模板中使用{{comment_form}}

但你像那样return render(request,'post.html',{"form":comment_form,})进行渲染。

在您的模板中,您需要使用{{form}}来调用它,因为这是您传递的内容。

<form method="POST" action="">{% csrf_token %} 
{{form}}

  

您还必须实例化comment_form   if request.method == "POST":因为需要先定义表单。只需删除它。一切都应该有效。