Filtering a model in a CreateView with get_queryset

前端 未结 1 1804
后悔当初
后悔当初 2020-12-14 05:08

I\'m trying to filter a model with get_queryset() and it seems to work in the view but not in the template.

My view :

class FolderCreate(CreateView):         


        
相关标签:
1条回答
  • 2020-12-14 05:28

    The issue here is that get_queryset is not used in a CreateView, as it's meant for filtering the models returned for display in a list or detail view. You want something completely different: you want to filter the choices available in a form field.

    To do that you will need to create a custom ModelForm that accepts a user kwarg and filters the queryset accordingly:

    class FolderForm(forms.ModelForm):
        class Meta:
           model = Folder
           fields = ['name', 'parent']
    
        def __init__(self, *args, **kwargs):
           user = kwargs.pop('user')
           super(FolderForm, self).__init__(*args, **kwargs)
           self.fields['parent'].queryset = Folder.objects.filter(user=user)
    

    and then change your view to use that form and pass in the user parameter:

    class FolderCreate(CreateView):
        template_name = 'Form/folder_create.html'
        form_class = FolderForm
    
        def get_form_kwargs(self):
            kwargs = super(FolderCreate, self).get_form_kwargs()
            kwargs['user'] = self.request.user
            return kwargs
    
    0 讨论(0)
提交回复
热议问题