Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django init function with attrs in Form

im using Django Profiles, and i need to make some change in the profile form.

In the normal way my form is fine completly, but now i would like a litter change, add jquery for repopulate a select form.

The problem is that Django Profile make the form from the model, so i would like to add a attribute id to the select form (i did yet), but then the select dont show me the options (values), i dont understand why, the select form bring the value from another model with FK.

Thanks guys :), Sorry with my English

my custom part is :

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
like image 684
Asinox Avatar asked Apr 28 '26 16:04

Asinox


1 Answers

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.

like image 73
vinyll Avatar answered Apr 30 '26 07:04

vinyll