Django:为什么manytomany选择框只有一边 [英] Django: why the manytomany choice box only has on side

查看:199
本文介绍了Django:为什么manytomany选择框只有一边的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经扩展了组模型,在那里我添加了一些manytomany字段,在管理页面中,它喜欢这样:

I have extended the group model, where I added some manytomany fields, and in the admin page, it likes this:

但是,我预期的是这样的:

However, what I expected is this:

这是我如何实现m2m字段:

Here is how I implemented the m2m field:

class MyGroup(ProfileGroup):
    mobile = models.CharField(max_length = 15)
    email = models.CharField(max_length = 15)
    c_annotates = models.ManyToManyField(Annotation, verbose_name=_('annotation'), blank=True, null=True)
    c_locations = models.ManyToManyField(Location, verbose_name=_('locations'), blank=True, null=True)

在数据库中有一个包含group_id和location_id对的关系形式。

And in the database there is a relational form which contains the pairs of group_id and location_id.

有谁知道如何做它?谢谢!

Is there anyone who knows how to do it? Thanks!

编辑:

我如上所述实现了多个选择框实际显示,但无法保存...(对不起,我正在使用虚拟机,现在已经离线了,所以我必须从屏幕剪辑代码)

I implemented as above, the multiple select box actually shows up, but it cannot save... (Sorry, I was working on a virtual machine and it's offline now, so I have to clip the code from screen)

推荐答案

问题解决了。现在可以保存多选字段。

Problem solved. It can save the multiple choice field now.

class GroupAdminForm(forms.ModelForm):
    users = forms.ModelMultipleChoiceField(queryset=User.objects.all(),
                                       widget=FilteredSelectMultiple('Users', False),
                                       required=False)
    locations = forms.ModelMultipleChoiceField(queryset=Location.objects.all(),
                                       widget=FilteredSelectMultiple('Location', False),
                                       required=False)
    class Meta:
        model = Group

    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance', None)
            if instance is not None:
            initial = kwargs.get('initial', {})
            initial['users'] = instance.user_set.all()
            initial['locations'] = instance.c_locations.all()
            kwargs['initial'] = initial
        super(GroupAdminForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        group = super(GroupAdminForm, self).save(commit=commit)

        if commit:
            group.user_set = self.cleaned_data['users']
            group.locations = self.cleaned_data['locations']
        else:
            old_save_m2m = self.save_m2m
            def new_save_m2m():
                old_save_m2m()
                group.user_set = self.cleaned_data['users']
                group.location_set = self.cleaned_data['locations']
            self.save_m2m = new_save_m2m
        return group

这篇关于Django:为什么manytomany选择框只有一边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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