milandjukic88
milandjukic88

Reputation: 1115

ModelForm in django, how to get maxlength attribute

In context i have form. When I put {{form}} in HTML page, everything is ok. Something like this:

<input id="id_sifraDrzave" maxlength="1024" name="sifraDrzave" type="text" />

How to get maxlength of field?

Upvotes: 4

Views: 1605

Answers (2)

falsetru
falsetru

Reputation: 369094

You can access it using form.fields.username.max_length in template.

Example (interactive shell):

>>> from django.forms.models import modelform_factory
>>> from django.contrib.auth.models import User
>>> UserForm = modelform_factory(User)
>>> form = UserForm({})
>>> print form['username']
<input id="id_username" maxlength="30" name="username" type="text" />
>>> print form.fields['username'].max_length
30

>>> from django.template import Template, Context
>>> print Template('{{ form.fields.username.max_length }}').render(Context({'form': form}))
30

Or use <specific_column>.field.max_length:

>>> print Template(
... '{% for column in form %}{{ column.field.max_length }} {% endfor %}'
... ).render(Context({'form': form}))
128     30 30 30 75

Upvotes: 3

milandjukic88
milandjukic88

Reputation: 1115

{% for column in  columnMetaData%}
        alert('{{column}}');
        alert('{{column.max_length}}');
{% endfor %}

first alert displays:

<input id="id_sifraDrzave" maxlength="1024" name="sifraDrzave" type="text" />

second alert nothing...

Upvotes: 1

Related Questions