Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to dynamically render a hidden version of a django field in a template?

Introspection tells me that django fields have a "hidden_widget" attribute. Maybe its not this attribute's given purpose, but its mere existence tempts me to use it in a template to conditionally render a hidden widget. e.g.,

{% if some condition %} 
   {{ form.my_field }} 
{% else %} 
   {{ form.my_field.hidden_widget }} 
{% endif %}

But this doesn't work. Is it possible to use the hidden widget this way? What am I missing?

I realize I could do this by dynamically setting the widget in the init of my custom Form class based on some custom kwarg for the conditional, which I pass in to it, but the above solution (dynamically rendering the hidden widget in the template) would be way simpler, if its available.

like image 411
B Robster Avatar asked Mar 29 '12 04:03

B Robster


People also ask

What is DTL in Django?

Django Template Language (DTL) is the primary way to generate output from a Django application. You can include DTL tags inside any HTML webpage. The basic DTL tag you can include in an HTML webpage is: 1. {% Tag %}

What is form AS_P in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.

What {{ NAME }} means in a Django template?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What is block content in Django?

In master templates the block tag is a placeholder that will be replaced by a block in a child template with the same name. In child templates the block tag is content that will replace the placeholder in the master template with the same name.


1 Answers

I was close, but using the wrong function. The answer, for those who are interested, is:

{{ form.my_field.as_hidden }}
like image 73
B Robster Avatar answered Sep 22 '22 09:09

B Robster