ModelForm不显示输入字段

时间:2014-05-12 16:21:38

标签: django django-forms

我正在努力在Django的视图中显示字段。 出现提交按钮,但与模型相关的字段会出现 不。 这是我的代码:

Forms.py

from django.forms import ModelForm
from blog.models import Comments

class CommentForm(ModelForm):
    class Meta:
        model = Comments

Models.py

class Comments(models.Model):
    entries_id = models.ForeignKey(Entries)
    author = models.CharField(max_length=40)
    text = models.TextField()
    created_on = models.DateTimeField("date published")

Views.py

class CommentListView(ListView):

    model = Comments

    def get_context_data(self, **kwargs):
        context = super(CommentListView, self).get_context_data(**kwargs)
        context['now'] = timezone.now()
        return context
    def add_comment(self, request, *args, **kwargs):
        if request.method == 'GET':
            form = CommentForm()

        elif request.method == 'POST':
            form = CommentForm(request.POST.copy())
            if form.is_valid():
                context = dict(form = form)
            return render_to_response('comments_list.html', context) # etc.

模板:

{% extends 'flatpages/default.html' %}


    {% block body %}

    {% for Comments in object_list reversed %}
    <p>{{ Comments.text }} </p></br>
    <p>{{ Comments.author }}</p>

{% empty %}
    <p>No comments yet</li></p>
{% endfor %}

<div="form" >    
<form method = 'post' action =''> {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
   </form>
 </div>
    {% endblock %}   

我将不胜感激任何帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

您并不总是为表单赋予价值。至少,我会这样做:

def get_context_data(self, **kwargs):
    context = super(CommentListView, self).get_context_data(**kwargs)
    context['now'] = timezone.now()
    context['form'] = CommentForm()
    return context