如何在 django 中为选项标签添加属性? [英] How to add attributes to option tags in django ?

查看:25
本文介绍了如何在 django 中为选项标签添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将 title 属性添加到 ModelChoiceField 的选项中.这是我的管理代码:

I have to add title attribute to options of the ModelChoiceField. Here is my admin code for that:

class LocModelForm(forms.ModelForm):
        def __init__(self,*args,**kwargs):
            super(LocModelForm,self).__init__(*args,**kwargs)
            self.fields['icons'] = forms.ModelChoiceField(queryset = Photo.objects.filter(galleries__title_slug = "markers"))
            self.fields['icons'].widget.attrs['class'] = 'mydds'


        class Meta:
            model = Loc
            widgets = {
                'icons' : forms.Select(attrs={'id':'mydds'}), 
                }

        class Media:
            css = {
                "all":("/media/css/dd.css",)
                }
            js=(
                '/media/js/dd.js',
                )

class LocAdmin(admin.ModelAdmin):
    form = LocModelForm

我可以添加任何属性来选择小部件,但我不知道如何向选项标签添加属性.任何的想法 ?

I can add any attribute to select widget, but i don't know how to add attributes to option tags. Any idea ?

推荐答案

首先不要修改__init__中的字段,如果你想覆盖widgets使用Meta> 内部类,如果要覆盖表单字段,请像在普通(非模型)表单中一样声明它们.

First of all, don't modify fields in __init__, if you want to override widgets use Meta inner class, if you want to override form fields, declare them like in a normal (non-model) form.

如果 Select 小部件不能满足您的需求,那么只需制作您自己的小部件.原始小部件使用 render_option 获取单个选项的 HTML 表示的方法——创建一个子类,覆盖它,然后添加任何你想要的.

If the Select widget does not do what you want, then simply make your own. Original widget uses render_option method to get HTML representation for a single option — make a subclass, override it, and add whatever you want.

class MySelect(forms.Select):
    def render_option(self, selected_choices, option_value, option_label):
        # look at the original for something to start with
        return u'<option whatever>...</option>'

class LocModelForm(forms.ModelForm):
    icons = forms.ModelChoiceField(
        queryset = Photo.objects.filter(galleries__title_slug = "markers"),
        widget = MySelect(attrs = {'id': 'mydds'})
    )

    class Meta:
        # ...
        # note that if you override the entire field, you don't have to override
        # the widget here
    class Media:
        # ...

这篇关于如何在 django 中为选项标签添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆