Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

django - Filtering a model in a CreateView with get_queryset

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):
    fields = ['name', 'parent']
    template_name = 'Form/folder_create.html'

    def get_queryset(self):
        folders = Folder.objects.filter(owner=self.request.user) 
        print folders # ==> return [<Folder: Folder>, <Folder: Another folder>]
        return folders

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.owner = self.request.user
        return super(FolderCreate, self).form_valid(form)

    def get_initial(self):
        if self.request.method == 'GET':
            foldersUrl = self.request.META['HTTP_REFERER'].split('/')
            foldersUrl.pop()
            folder = urllib2.unquote(foldersUrl[-1])

            try:
                return {'parent' : Folder.objects.get(name=folder, owner=self.request.user)}
            except Folder.DoesNotExist:
                pass

As you can see, folders return two objects related to the session user in get_queryset() : 'Folder' and 'Another folder

Infortunately, the combobox of my template get all the folders, without any filtering.

enter image description here

Any idea ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...