Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does {{ field }} display a field widget in a django template?

Tags:

python

django

According to my understanding of the django template language, {{ variable }} will display that variable by one of the following ways:

  1. The variable is a string itself
  2. The variable is a callable that returns a string
  3. The string representation of the variable

A demonstration session:

>>> from django.template import Template, Context
>>> template = Template("Can you display {{ that }}?")
>>> context = Context({"that":"a movie"})          #a string variable
>>> template.render(context)
u'Can you display a movie?'
>>> context2 = Context({"that": lambda:"a movie"}) #a callable
>>> template.render(context2)
u'Can you display a movie?'
>>> class Test:
...   def __unicode__(self):
...     return "a movie"
... 
>>> o = Test()
>>> context3 = Context({"that":o}) #the string representation
>>> template.render(context3)
u'Can you display a movie?'

Obviously, form fields are not any of these cases.

Demonstration session:

>>> from django import forms
>>> class MyForm(forms.Form):
...   name = forms.CharField(max_length=100)
... 
>>> form = MyForm({"name":"Django"})
>>> name_field = form.fields["name"]
>>> name_field #a string variable?
<django.forms.fields.CharField object at 0x035090B0>
>>> str(name_field) #the string represetation?
'<django.forms.fields.CharField object at 0x035090B0>'
>>> name_field() #a callable?
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'CharField' object is not callable
>>> context4 = Context({"that":name_field})
>>> template.render(context4)
u'Can you display &lt;django.forms.fields.CharField object at 0x035090B0&gt;?'

Take a look at that last bit, it doesn't actually render like a real template.

Then how such a template correctly displays a form:

{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
    </div>
{% endfor %}

How are fields converted to their corresponding widgets in that case?

like image 635
MadeOfAir Avatar asked Dec 01 '25 10:12

MadeOfAir


1 Answers

It all comes down to:

>>> str(form['name'])
'<input id="id_name" type="text" name="name" value="Django" maxlength="100" />'

I guess that's what the for loop in your template iterates over.

like image 91
Dunno Avatar answered Dec 04 '25 01:12

Dunno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!