微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

多对多字段的Djano管理表单查询集

如何解决多对多字段的Djano管理表单查询集

一个如何在 init 添加request.user并保存方法 我想使用所有者= request.user。目前,我已在 init 中将其硬编码为owner = 2

class QuizAdminForm(forms.ModelForm):
   
    class Meta:
        model = Quiz
        exclude = []
        

    questions = forms.ModelMultipleChoiceField(
        queryset=Question.objects.filter(owner=1).select_subclasses(),required=False,label=_("Questions"),widget=FilteredSelectMultiple(
            verbose_name=_("Questions"),is_stacked=False))

    def __init__(self,*args,**kwargs,):         
        super(QuizAdminForm,self).__init__( *args,**kwargs)               
        if self.instance.pk:
            print('filter questions')
            self.fields['questions'].initial =\
                self.instance.question_set.filter(owner= 2).select_subclasses()            
    
    def save(self,commit=True):
        quiz = super(QuizAdminForm,self).save(commit=False)                
        quiz.save()
        quiz.question_set.set(self.cleaned_data['questions'])
        self.save_m2m()
        return quiz


class QuizAdmin(admin.ModelAdmin):
    form = QuizAdminForm

    list_display = ('title','category',)
    list_filter = ('category',)
    search_fields = ('description',)

我还想添加owner = request.user,我可以使用以下方法进行添加。但是在那种情况下,question_set.set无法正常工作,在“ save”方法中可以正常工作。

def save_model(self,request,obj,form,change):
        if not obj.pk:
        # Only set added_by during the first save.
            obj.owner = request.user
            super().save_model(request,change)
        quiz = Quiz.objects.get(id=obj.id)               
        quiz.save()
        quiz.question_set.set(self.cleaned_data['questions'])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。