【问题标题】:django - simple way to re-use form to just display data?django - 重用表单来显示数据的简单方法?
【发布时间】:2011-12-13 03:18:50
【问题描述】:

我创建了一个包含许多字段的表单。在另一个视图中,我需要显示在表单中输入的数据。有没有一种简单的方法可以重用表单,但这次显示输入的数据(即“只读”)?

【问题讨论】:

    标签: django django-templates django-views


    【解决方案1】:

    您可以子类化您的表单并使用属性disabled 设置所有表单小部件。或者将所有字段设置为仅呈现文本且没有输入框的小部件(如 django admin readonly 小部件)。

    class ReadOnlyForm(MyForm):
        def __init__(self, *args, **kwargs):
            super(ReadOnlyForm, self).__init__(*args, **kwargs)
            for field in self.fields.values():
                field.widget.attrs['disabled'] = 'true' # or replace the widget
                # with one that just returns the value in plain html
    
    readonly_form = ReadOnlyForm(the_data)
    

    【讨论】:

      【解决方案2】:

      另一种方法是控制表单的呈现方式:

      {% for field in form %}
              {{ field.label }}: {{ field.value }}
      {% endfor %}
      

      【讨论】:

      • 谢谢 - 我知道这是如何工作的,但我更喜欢 Yuji Tomita 的回答,因为它允许我重复使用我的模板。
      猜你喜欢
      • 2014-06-13
      • 1970-01-01
      • 2021-08-13
      • 2018-01-08
      • 2011-08-03
      • 2022-08-04
      • 2013-11-17
      • 1970-01-01
      • 2012-12-15
      相关资源
      最近更新 更多