Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django with super and Init

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are just adding the class "input" to all fields in your form:

<input type="text" class="input" .... ....>

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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading