سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

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" />
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top