【问题标题】:Django Template Form RenderDjango 模板表单渲染
【发布时间】:2013-10-10 08:22:27
【问题描述】:

我的问题是不在模板上显示 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

                   }
                  )

【问题讨论】:

  • 您没有在上下文中传递form。就这样

标签: django forms field render


【解决方案1】:

在您看来,您没有向模板发送任何上下文变量,因此您的“表单”对象无法供您的模板处理。

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

from django.shortcuts import render

...

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

您还可以传递字典而不是所有局部变量。这是render的文档

【讨论】:

    【解决方案2】:

    您忘记实例化表单,更改此行:

    'form': CommentForm,
    

    到这里

    'form': CommentForm(),
    

    【讨论】:

      猜你喜欢
      • 2022-07-22
      • 2016-08-23
      • 2018-05-20
      • 2018-11-05
      • 2020-04-25
      • 2012-03-18
      • 2017-05-25
      • 2015-09-17
      • 2020-02-10
      相关资源
      最近更新 更多