Django с super и Init
Я не понимаю этот код. Я смотрю несколько учебников по python/django. Надеюсь, вы сможете меня просветить.
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'})
что делает этот код?
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
Спасибо
Вы просто добавляете класс "input" ко всем полям в вашей форме:
<input type="text" class="input" .... ....>
В последних версиях Django вам не нужно указывать класс в super, вы можете сделать так:
super().__init__(*args, **kwargs)
Вы можете использовать def init, например, чтобы изменить атрибуты по умолчанию ваших полей:
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
Подробнее о def "init" можно узнать здесь: https://docs.djangoproject.com/en/dev/howto/custom-model-fields/