2013-10-03 170 views
1

我的问题不是在模板上显示django表单域。这很愚蠢,但我只是没有找到任何解决方案。Django模板窗体渲染

class CommentForm(forms.ModelForm): 

    class Meta: 
     model = Comment 
     fields = ['name', 'email', 'text'] 

    def __init__(self, content_type, id, *args, **kwargs): 
     super(CommentForm, self).__init__(*args, **kwargs) 
     self.content_type = content_type 
     self.id = id 

    def save(self, commit=True): 

     post_type = ContentType.objects.get_for_model(Post) 
     comment_type = ContentType.objects.get_for_model(Comment) 
     comment = super(CommentForm, self).save(commit=False) 

     if self.content_type == 'post': 
      comment.content_type = post_type 
      comment.post = self.id 
     else: 
      parent = Comment.objects.get(id=self.id) 
      comment.content_type = comment_type 
      comment.post = parent.post 

     comment.object_id = self.id 


     if commit: 
      comment.save() 

     return comment 

我的观点:

def add_comment(request, content_type, id): 

    if request.method == 'POST': 
     data = request.POST.copy() 
     form = CommentForm(content_type, id, data) 
     if form.is_valid(): 
      form.save() 

    return redirect(reverse('index')) 

我add_comment模板:

<form method="post" action="{% url 'add_comment' 'post' post.id %}"> 
    {% csrf_token %} 

    {% if not user.is_authenticated %} 
    {{ form.name.label_tag }} 
    {{ form.name }} 

    {{ form.email.label_tag }} 
    {{ form.email }} 
    {% endif %} 


    {{ form.text.label_tag }} 
    {{ form.text }}<br> 


    <input type="submit" value="Comment" /> 

    </form> 

和我包括像:

<button id="button" type="button">Add Comment</button> 
    <div id="post_comment_form">{% include 'articles/add_comment.html' %}</div> 
</article> <!-- .post.hentry --> 

为什么不Django的渲染表单域,尽管显示的纽扣?

编辑:

我呈现形式后视图。

def post(request, slug): 

    post = get_object_or_404(Post, slug=slug) 
    comments = Comment.objects.filter(post=post.id) 


    return render(request, 
        'articles/post.html', 
        {'post': post, 
        'form': CommentForm, 
        'comments': comments, 
        # 'child_comments': child_comments 

        } 
       ) 
+1

你是不是在传递上下文中的'form'。这就是你 – karthikr

回答

1

的文档,你忘了实例的形式,改变这一行:

'form': CommentForm, 

这个

'form': CommentForm(), 
0

在您看来,您并未向模板发送任何上下文变量,因此您的“表单”对象不可用于模板进行处理。

例如,以下return语句将呈现.html并传递所有局部变量,但这不一定是最佳选项(您希望模板有多少访问权限),但很简单:

from django.shortcuts import render 

... 

return render(request, "template.html", locals()) 

您还可以传递字典而不是所有局部变量。下面是render