[Django]-Django init function with attrs in Form

3👍

What you really should do is to deal with your jquery trhough Javascript, not through python !

Javascript

So import a js file with something like this :

$(function(){
  $('#id_sector').onchange(function(){
    get_vehicle_color();
  })
})

Django form html attribute

For those who actually need to set an attribute to a form field, you can do it as so :

def __init__(self, *args, **kwargs):
    super(_ProfileForm, self).__init__(*args, **kwargs)
    self.fields['sector'].widget.attrs = {'my_attribute_key':'my_attribute_value'}

This way is cleaner as you don’t override the widget and get your head off when modifying your model or Form class attributes.

👤vinyll

1👍

Try this:

 class _ProfileForm(forms.ModelForm):
     birth_date = forms.DateTimeField(
         widget = SelectDateWidget(years=range(datetime.date.today().year,1900,-1))
     )
     sector = forms.ChoiceField(
         widget = Select(attrs={'onchange':'get_sector_code();'})
     )

     class Meta:
         model = profile_mod
         exclude = ('user',) # User will be filled in by the view.
👤David

Leave a comment