【问题标题】:django init function with attrs in Form表单中带有 attrs 的 django init 函数
【发布时间】:2009-09-18 05:02:25
【问题描述】:

我正在使用 Django 配置文件,我需要在配置文件表单中进行一些更改。

在正常情况下,我的表单完全没问题,但现在我想换个垃圾,添加 jquery 以重新填充选择表单。

问题是 Django Profile 从模型中创建表单,所以我想在选择表单中添加一个属性 id(我还没有),但是然后选择不显示选项(值),我没有明白为什么,选择表单会从另一个带有 FK 的模型中获得价值。

谢谢大家 :), 对不起我的英语

我的自定义部分是:

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

【问题讨论】:

    标签: django django-models django-forms


    【解决方案1】:

    你真正应该做的是通过 Javascript 处理你的 jquery,而不是通过 python!

    Javascript

    所以导入一个类似这样的 js 文件:

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

    Django 表单 html 属性

    对于那些真正需要为表单字段设置属性的人,您可以这样做:

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

    这种方式更简洁,因为您不会在修改模型或 Form 类属性时覆盖小部件并且不注意。

    【讨论】:

    • 如果我使用第二种方法,我的 form.is_valid() 在视图中总是给出 false 并且数据似乎没有通过。只是说,因为我没有找到一个明确的解决办法。我正在使用 class Meta: model = Profile widgets = { 'sector': forms.NumberInput(attrs={'my_attribute_key':'my_attribute_value'}), } 这确实有效......哇,问题似乎是我有: def __init__(self, request, *args, **kwargs): 没有对请求变量做任何事情!
    • 我会改用self.fields['sector'].widget.attrs.update({'my_attribute_key':'my_attribute_value'}),以免覆盖其他地方设置的属性。
    【解决方案2】:

    试试这个:

     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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 2021-05-24
      • 2019-12-09
      • 2017-01-04
      • 2017-07-06
      • 2011-01-18
      • 2012-02-22
      相关资源
      最近更新 更多