【问题标题】:How to assign a value to a django form field in the template?如何为模板中的 django 表单字段赋值?
【发布时间】:2015-05-13 17:38:39
【问题描述】:

我想知道如何为模板中的 django 表单字段赋值。

我知道在django中还有其他的方法可以给初始值赋值,但是我需要在模板中赋值,因为变量只存在于模板中。

使用普通 html 表单执行此操作的方法如下:

{% for thing in things %}
  <p> {{ thing.content }} </p>
  <!-- Reply form -->
  <form>
    <input type="hidden" name="replyingto" value="{{ thing.number }}">
    <input type="text" label="Reply"></input>
  </form>
{% endfor %}

但是,我需要使用 django 表单。

我也知道有一种方法可以为模板中的字段分配标签,如下所示:

{{ form.non_field_errors }}
{{ form.field.errors }}
   <label for="{{ form.field.id_for_label }}"> field </label>
{{ form.field }}

所以我的问题基本上是您将如何执行上面的示例,而不是分配标签,而是分配一个值。


我找到了解决办法!

我所做的是按照Daniel 的建议手动键入 html 并以这种方式分配值。

如果有人想知道我是如何做到的,请联系example

【问题讨论】:

  • 我不明白你的代码有什么问题。手动创建 HTML 不会阻止您在视图中使用 Django 表单。
  • 对不起,我不明白。我可以使用 html 表单而不是 django 表单并在视图中解析这些值吗?
  • 如果你愿意,但你说你想使用 Django 表单。
  • 好吧,如果有办法从普通的 html 表单解析值,我真的不需要 django 表单。如果有办法,我的问题是你将如何做到这一点。
  • 你能添加这个页面的views.py和forms.py代码吗?我敢肯定,在代码中有更好的方法来做到这一点。

标签: python html django


【解决方案1】:

您可以在 Python 中执行此操作,然后可用于 HTML 表单或生成器

forms.py中可以设置initial属性来定义字段的默认值。

例如:name = forms.CharField(initial='class')

或在views.py 中动态使用dict

例如:f = CommentForm(initial={'name': 'instance'})

一旦在form 实例中可用,您就可以使用{{ form.field.value }} 在您的 HTML 中或使用生成器自动生成

扩展参考:https://docs.djangoproject.com/en/1.10/ref/forms/api/#s-dynamic-initial-values

【讨论】:

    【解决方案2】:

    您可以逐个字段手动渲染表单,然后使用 Django 模板插值渲染所有其他字段,但您可以手动渲染隐藏字段。例如

    {% for thing in things %}
      <p> {{ thing.content }} </p>
      <!-- Reply form -->
      <form FORM_PARAMS_HERE >
        <div class="form-row">
            {{ form.other_form_field.errors }}
            {{ form.other_form_field.label_tag }} {{ form.other_form_field }}
        </div>
        ... (more form rows)
        <div class="form-row">
            <input type="hidden" name="replyingto" id="replyingto_id" value="{{ thing.number }}">
            <input type="text" label="Reply"></input>
        </div>
      </form>
    {% endfor %}
    

    我遇到了这个确切的问题,并且在找到this excellent and hard to find reference 之后,终于能够按照我认为您想要的方式解决它。

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 2011-01-15
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 2011-12-30
      相关资源
      最近更新 更多