4

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?

R-obert
  • 553
  • 4
  • 13
  • What does your template look like. Is it just referencing `{{ form }}` or are you referencing the fields individually? – michjnich Oct 20 '20 at 11:30

2 Answers2

4

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'})
aberkb
  • 664
  • 6
  • 12
2

The type of the widget is determined by the .input_type attribute, so:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['birth_date'].widget.input_type = 'date'

This is however often not a good idea, since other items of the widget are then not altered correctly. Normally you specify the widget in the Meta class:

class MyForm(forms.ModelForm):
    
    class Meta:
        model = Meta
        widgets = {
            'birth_date': forms.DateInput()
        }

But if the widget is not a DateInput, then likely the field birth_date in your model is not a models.DateField, so it might be better to fix this instead of solving it at the widget level.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Your first block of code is what I came up with too, after a while (and still no idea why you can edit all other HTML tag attributes via `attrs.update` except for the type). Isn't it common practice to edit fields in the constructor? I didn't know there were other rules for the form fields' widget attribute. – R-obert Oct 22 '20 at 12:51