I dont understand this code. I'm watching couple of tutorial for python/django tutorial. Hope you guys can enlighten me.
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['name', 'email', 'username',
'location', 'bio', 'short_intro', 'profile_image',
'social_github', 'social_linkedin', 'social_twitter',
'social_youtube', 'social_website']
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
what does this code do?
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
Thanks
CodePudding user response:
You are just adding the class "input" to all fields in your form:
<input type="text" .... ....>
In the latest Django versions you don't need to specify the class in super, you can do this:
super().__init__(*args, **kwargs)
You can use def init, for example, to change the default attributes of your fields:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs['class'] = 'input' #same as your code
self.fields['email'].widget.attrs['required'] = True #required argument to the email field
You can learn more about def "init" here: https://docs.djangoproject.com/en/dev/howto/custom-model-fields/