如何在模板中显示Django表单字段的值? [英] How do I display the value of a Django form field in a template?
问题描述
我有一个带有电子邮件属性的表单。
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屋!