David542
David542

Reputation: 110163

Django fields in django-registration

I am setting up django registration, and I came across this piece of code in the RegistrationForm --

attrs_dict = { 'class': 'required' }

email = forms.EmailField(widget=forms.TextInput
                        (attrs=dict(attrs_dict, maxlength=75)),
                        label='Email')

What does the part (attrs=dict(attrs_dict, maxlength=75)) mean/do? I know what the maxlength part does but was unclear what the creation of a dictionary is doing, and what the attrs_dict is doing. Any explanation of this piece of code would be great. Thank you.

Upvotes: 0

Views: 313

Answers (3)

Akshar Raaj
Akshar Raaj

Reputation: 15211

Each form field in django uses a widget. You can either specify it during field creation or a default widget is used.

Here you are specifying widget TextInput on EmailField

(attrs=dict(attrs_dict, maxlength=75)) becomes:

{'class': 'required', 'maxlength':75}

Now these will be present as attributes in the rendered html for this widget. So, rendered html for field email would look like:

<input id="id_email" type="text" class="required" maxlength="75" name="email" />

Upvotes: 0

Rohit
Rohit

Reputation: 1918

It is creating a dictionary of attributes which will be required to add validation kind of things in finally rendered form, in this way we dont need to do anything in the template code to add validation and security.

Upvotes: 0

LeafGlowPath
LeafGlowPath

Reputation: 3799

A bit of test showed that dict(attr_dict, maxlenght=75) equals to

{'class': 'required', 'maxlength':75}

So when the email filed is rendered to an html element, 2 attributes, class and maxlength will be added to the label.

Upvotes: 1

Related Questions