django init function with attrs in Form

余生长醉 提交于 2019-12-21 03:13:44

问题


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

回答1:


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.




回答2:


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.


来源:https://stackoverflow.com/questions/1442681/django-init-function-with-attrs-in-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!