简体   繁体   English

django admin中带有django-taggit字段的FilteredSelectMultiple小部件

[英]FilteredSelectMultiple widget with django-taggit field in django admin

I am trying to add Tags to my model instances using django-taggit's package. 我正在尝试使用django-taggit's软件包将Tags添加到我的模型实例中。 For this I have added the tags field in my Model as it is defined in django-taggit's definition. 为此,我在django-taggit's定义中定义的模型中添加了tags字段。

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    tags = TaggableManager()

I want to add this model to django-admin panel and want to use FilteredSelectMultiple widget for adding tags. 我想将此模型添加到django-admin面板,并想使用FilteredSelectMultiple小部件添加标签。 for this I have created a model form and changed it's field's widget. 为此,我创建了一个模型表单并更改了它的字段小部件。

class MyModelForm(forms.ModelForm):
    tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.none())
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['tags'].widget = FilteredSelectMultiple('Tags', False)
        self.fields['tags'].queryset = Tag.objects.all()

class Meta:
    model = MyModel
    exclude = []

class MyModelAdmin(admin.ModelAdmin): form = MyModelForm 类MyModelAdmin(admin.ModelAdmin):form = MyModelForm

everything is working fine. 一切正常。 Tags are being saved after saving the instace. 保存实例后将保存标签。 but the problem is that when I am opening the update page. 但是问题是当我打开更新页面时。 There are no previously selected tags in 'Chosen Tags' part of the field's widget.It is empty and all the choices are in 'Available tags' option. 字段小部件的``选择标签''部分没有先前选择的标签,该标签为空,所有选项均在``可用标签''选项中。

I tried to provide initial data also for the change_form of model admin but nothing works for me. 我也尝试为模型admin的change_form提供初始数据,但对我没有任何帮助。

def get_changeform_initial_data(self, request):
    return {'tags': self.object.tags.all()}

self.object is the object which i got by get_object() method of the ModelAdmin class. self.object是我通过ModelAdmin类的get_object()方法获得的ModelAdmin

Give me a solution. 给我一个解决方案。

Seems the problem is that the prepare_value function in ModelMultipleChoiceField looks at the .pk field on the object which gives a value that's incorrect so it does not render (or renders the wrong selection). 似乎问题在于,ModelMultipleChoiceField中的prepare_value函数查看对象上的.pk字段,该字段给出的值不正确,因此不会呈现(或呈现错误的选择)。 You should be looking at it's .tag_id field. 您应该查看它的.tag_id字段。

This worked for me but would be interested if there is a more correct or elegant way: 这对我有用,但是如果有更正确或更优雅的方法,可能会感兴趣:

class TagMultipleChoiceField(forms.ModelMultipleChoiceField):
    def prepare_value(self, value):
        if hasattr(value, 'tag_id'):
            return value.tag_id
        elif hasattr(value, '__iter__') and not isinstance(value, six.text_type) and not hasattr(value, '_meta'):
            return [self.prepare_value(v) for v in value]
        else:
            return super(TagMultipleChoiceField, self).prepare_value(value)

class AdminCourseForm(forms.ModelForm):
    class Meta:
        model = Course
        exclude = ()

    tags = TagMultipleChoiceField(queryset=MyTag.objects.all())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM