本文介绍了使用 get_queryset 过滤 CreateView 中的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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.

我的观点:

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

如您所见,文件夹在 get_queryset() 中返回与会话用户相关的两个对象:文件夹"和另一个文件夹"

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.

有什么想法吗?

推荐答案

这里的问题是 get_queryset 没有在 CreateView 中使用,因为它用于过滤返回的模型以显示在列表中或详细视图.您想要完全不同的东西:您想要过滤表单字段中可用的选项.

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.

为此,您需要创建一个接受 user kwarg 并相应地过滤查询集的自定义 ModelForm:

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

这篇关于使用 get_queryset 过滤 CreateView 中的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:36