如何在模板中显示 Django 表单字段的值? [英] How do I display the value of a Django form field in a template?

查看:29
本文介绍了如何在模板中显示 Django 表单字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有电子邮件属性的表单.

I have a form with an email property.

当使用 {{ form.email }} 时,在一些验证错误的情况下,Django 仍然在输入标签的 value 属性中呈现前一个值:

When using {{ form.email }} in case of some validation error, Django still renders the previous value in the input tag's value attribute:

<input type="text" id="id_email" maxlength="75" class="required"
       value="some@email.com" name="email">

我想自己渲染输入标签(添加一些 JavaScript 代码和一个错误类以防出错).例如,这是我的模板而不是 {{ form.email }}:

I want to render the input tag myself (to add some JavaScript code and an error class in case of an error). For example this is my template instead of {{ form.email }}:

<input type="text" autocomplete="on" id="id_email" name="email"
       class="email {% if form.email.errors %} error {% endif %}">

然而,这不会向用户显示错误的值(在本例中为some@email.com).

However, this does not display the erroneous value (some@email.com in this example) to the user.

如何在模板中获取字段的值?

How do I get the field's value in the template?

推荐答案

Jens 提出的解决方案是正确的.但是,事实证明,如果您使用 instance(下面的示例)初始化 ModelForm,django 将不会填充数据:

The solution proposed by Jens is correct. However, it turns out that if you initialize your ModelForm with an instance (example below) django will not populate the data:

def your_view(request):   
    if request.method == 'POST':
        form = UserDetailsForm(request.POST)
        if form.is_valid():
          # some code here   
        else:
          form = UserDetailsForm(instance=request.user)

因此,我创建了自己的 ModelForm 基类来填充初始数据:

So, I made my own ModelForm base class that populates the initial data:

from django import forms 
class BaseModelForm(forms.ModelForm):
    """
    Subclass of `forms.ModelForm` that makes sure the initial values
    are present in the form data, so you don't have to send all old values
    for the form to actually validate.
    """
    def merge_from_initial(self):
        filt = lambda v: v not in self.data.keys()
        for field in filter(filt, getattr(self.Meta, 'fields', ())):
            self.data[field] = self.initial.get(field, None)

然后,简单的视图示例如下所示:

Then, the simple view example looks like this:

def your_view(request):   if request.method == 'POST':
    form = UserDetailsForm(request.POST)
    if form.is_valid():
      # some code here   
    else:
      form = UserDetailsForm(instance=request.user)
      form.merge_from_initial()

这篇关于如何在模板中显示 Django 表单字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆