简体   繁体   中英

Django: How to render form field by html_name

How can I render specific form field if I know its html_name ?

Lets say I have this form:

class MyForm(forms.Form):
    approve = forms.BooleanField()

Then form.fields['approve'].html_name == 'approve' . I tried in my template.html:

{{ form.fields.approve }}

But I get <django.forms.fields.BooleanField object at 0x2b2bf4503290> text rendered instead of input field.

form.fields holds the form.Field instances. You want the BoundField instances, which are accessible directly from the form instance using key access (in Python code) or dotted access (in template code). IOW:

in python:

form["approve"]

in templates :

{{ form.approve }}

Now note that it's not the html_name you have to use but the field name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM