我正在尝试使用get_queryset()过滤模型,它似乎在视图中工作但不在模板中。
我的观点:
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()中返回与会话用户相关的两个对象:'Folder'和'Another folder
幸运的是,我模板的组合框获取了所有文件夹,没有任何过滤。
有什么想法吗?
答案 0 :(得分:15)
这里的问题是get_queryset
未在CreateView中使用,因为它用于过滤返回的模型以在列表或详细视图中显示。您想要完全不同的东西:您想要过滤表单字段中的可用选项。
为此,您需要创建一个接受user
kwarg的自定义ModelForm并相应地过滤查询集:
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)
然后更改您的视图以使用该表单并传入用户参数:
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