Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ".widget.attrs.update" with NO effect

I have a ModelForm with the following init method:

def __init__(self, *args, **kwargs):
    super(FragebogenForm, self).__init__(*args, **kwargs)
    self.fields['birth_date'].widget.attrs.update({'type': 'date'})

This doesn't change the type attribute of the input tag, although it should according to the documentation (ctrl + f -> "Or if the field isn’t declared directly on the form"). If I change it to e.g. .widget.attrs.update({'placeholder': '12.12.1999'}) it works, the new placeholder appears on the page. Only setting the type to date does not work, but why?

like image 369
R-obert Avatar asked Sep 16 '25 15:09

R-obert


1 Answers

I just discovered my own error. I didn't put the initializer or __init__ outside the class metafunction. None of my widgets worked well ###Ensure the init block is outside

    class ProfileForm(ModelForm):
            class Meta:
                model = Profile 
                fields = ['avatar','company']  
        
    
 def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['avatar'].widget.attrs.update({'class': 'form-control'})
like image 98
Ajani Timothy Avatar answered Sep 19 '25 06:09

Ajani Timothy