Django init function with attrs in a form
im using Django Profiles and I need to make some changes to the profile form.
Normally my form is completely complete, but now I would like to change the litter, add jquery to repopulate the selected form.
The problem is the Django profile makes the form from the model, so I would like to add an attribute id to the select form (I did that yet), but then select dont show me options (values), I dont understand why the select form brings the value from another model using FK.
Thanks guys :), Sorry my english
my custom part:
def __init__(self, *args, **kwargs):
super(_ProfileForm, self).__init__(*args, **kwargs)
self.fields['birth_date'].widget = widget=SelectDateWidget(years=range(datetime.date.today().year,1900,-1))
self.fields['sector'].widget= forms.Select(attrs={'onchange':'get_vehicle_color();'})
Django-profiles / profiles / utils.py
#....
def get_profile_form():
"""
Return a form class (a subclass of the default ``ModelForm``)
suitable for creating/editing instances of the site-specific user
profile model, as defined by the ``AUTH_PROFILE_MODULE``
setting. If that setting is missing, raise
``django.contrib.auth.models.SiteProfileNotAvailable``.
"""
profile_mod = get_profile_model()
class _ProfileForm(forms.ModelForm):
class Meta:
model = profile_mod
exclude = ('user',) # User will be filled in by the view.
def __init__(self, *args, **kwargs):
super(_ProfileForm, self).__init__(*args, **kwargs)
self.fields['birth_date'].widget = widget=SelectDateWidget(years=range(datetime.date.today().year,1900,-1))
self.fields['sector'].widget= forms.Select(attrs={'onchange':'get_sector_code();'})
return _ProfileForm
source to share
What you really need to do is figure out jquery trhough Javascript, not 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 really need to set an attribute on a form field, you can do it like this:
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 because you don't override the widget or turn off the head when your model or Form class attributes change.
source to share
Try the following:
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.
source to share