显示模板中django表单字段的值? [英] Display value of a django form field in a template?

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

问题描述

我有一个包含电子邮件属性的表单。
如果出现某些验证错误,使用{{form.email}},django仍会在输入标签的value属性中显示以前的值:

 < input type =textid =id_emailmaxlength =75class =requiredvalue =some@email.comname =email> 

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

 < input type =textautocomplete = onid =id_emailname =emailclass =email {%if form.email.errors%} error {%endif%}> 

但是,这不会显示错误的值(在本例中为some@email.com)用户。
如何在模板中获取字段的值?

解决方案

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

  def your_view(request):if request.method =='POST':
form = UserDetailsForm(request.POST)
如果form.is_valid():
#这里的一些代码
else:
form = UserDetailsForm(instance = request.user)

所以,我做了自己的ModelForm基类填充初始数据:

 从django import forms 
class BaseModelForm(forms.ModelForm):

forms.ModelForm的子类确保表单数据中存在初始值


def merge_from_initial(self):
filt = lambda v:v不在self.data中.keys()
用于过滤器中的字段(filt,getattr(self.Meta,'fields', ())):
self.data [field] = self.initial.get(field,None)

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

  def your_view(request):if request.method = ='POST':
form = UserDetailsForm(request.POST)
如果form.is_valid():
#一些代码在这里
else:
form = UserDetailsForm instance = request.user)
form.merge_from_initial()


I have a form with an email property. 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">

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 %}">

However this does not display the errorneous value ("some@email.com" in this example) to the user. How do I get the field's value in the template?

解决方案

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)

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天全站免登陆