Djano Admin Forms queryset for ManyToMany Fields

409 views Asked by At

How does one add request.user in init and save methods I want to use owner = request.user. At the moment I have hardcoded in init as 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', 'category', )

I would also like to add owner=request.user, which I can do using the method below. But in that case question_set.set does not work which works fine in "save" method.

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, obj, form, change)
        quiz = Quiz.objects.get(id=obj.id)               
        quiz.save()
        quiz.question_set.set(self.cleaned_data['questions'])
0

There are 0 answers