【问题标题】:Reusable forms in Django appDjango 应用程序中的可重用表单
【发布时间】:2014-04-02 14:28:28
【问题描述】:

短:

我想创建一个应用程序,它提供格式良好的表单,可以导入到其他应用程序中。仅使用ModelForm 来执行此操作会导致部分成功,因为它仅呈现表单字段而没有任何额外需要的元素(如按钮)。然而,这也应该封装在应用程序中。

长:

为了更好地理解,假设我们有一个名为 blog 的应用程序和一个名为 comments 的应用程序。由于 cmets 也可以在其他地方和应用程序中使用,因此它们已被分开。 comments 应该提供一个表单,然后将其添加到 blog 的视图或模板中

所以这里有一些伪代码以便更好地理解。

cmets/models.py:

class Comment(models.Model):
    comment = models.TextField()
    author = models.CharField(max_length=64)

cmets/forms.py:

class CommentForm(forms.ModelForm)
    class Meta:
        model = Comment

cmets/templates/cmets/comment_form.html:

<form method="post" action="#">
    {{ formfields }}
    <button type="submit">Submit</button>
</form>

显然缺少一个步骤,因为ModelForm 和模板没有放在一起。我现在的目标是将这样的婚姻准确导入blog

blog/views.py

def render_article(request):
    context = {
        ...
        comment_form: <SOMETHING THAT CREATES A NICE TEMPLATE BASED HTML FORM>
    }

    return render(request, 'blog/article.html', context)

本质上,我正在寻找可以在任何类型的应用程序中使用的单个函数对象,以提供完整的表单。这样一来,它在所有应用中的外观总是相同的。

如何做到这一点?

【问题讨论】:

    标签: django django-forms django-templates


    【解决方案1】:

    您可以在表单中覆盖django.forms.Form.__unicode__

    from django.utils.safestring import mark_safe
    
    class MyForm(forms.Form):
       ...
       def __unicode__(self):
           html = super(MyForm, self).__unicode__
           html = html + '<button type="submit">Submit</button>'
           // or whatever — render a wrapper template, anything
           return mark_safe(html)
    

    【讨论】:

      猜你喜欢
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 2011-08-22
      • 2014-12-18
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      相关资源
      最近更新 更多