如何使用Django表单中的外键过滤选择值

时间:2016-05-23 04:15:11

标签: python django django-forms django-views

我有这个应用程序,我可以将文件上传到特定的类别或子类别。它工作正常,但我遇到的问题是当我试图仅为特定用户显示选择值时,对于特定的父类别,它只显示存储在数据库中的所有值。

views.py

class AddDocumentView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    login_url = reverse_lazy('users:login')
    form_class = FileUploadForm
    template_name = 'docman/forms/add-document.html'
    success_url = reverse_lazy('docman:index')
    success_message = 'Document was successfully added'

    def form_valid(self, form):
        profile = form.save(commit=False)
        profile.user = self.request.user
        return super(AddDocumentView, self).form_valid(form)

forms.py

class FileUploadForm(forms.ModelForm):
    file = forms.FileField()

    class Meta:
        model = Document
        exclude = ('user',)
        fields = [
            'file',
            'slug',
            'category',
        ]

    def __init__(self, user=None, **kwargs):
        super(FileUploadForm, self).__init__(**kwargs)
        if user:
            self.fields['category'].queryset = Category.objects.filter(user_id=user.id, parent_id=None)

我已经尝试过类似问题的解决方案,这就是我如何做到这一点,但它仍然没有被用户过滤,我无法弄清楚如何通过父ID过滤它。对我做错了什么想法?感谢任何帮助,如果需要,我可以提供更多信息。

-----------------解决方案更新-----------------

谢谢@solarissmoke我能够获取表单的用户信息。然后我做了同样的事情来使用kwargs从url捕获parent_id。

views.py

#  Override the view's get_form_kwargs method to pass the user and/or pk to the form:
def get_form_kwargs(self):
    pk = self.kwargs['pk']
    kwargs = super(AddDocumentView, self).get_form_kwargs()
    kwargs['user'] = self.request.user
    #  Check if category exists with pk, otherwise none
    if Category.objects.filter(parent_id=pk):
        kwargs['pk'] = pk
    else:
        kwargs['pk'] = None
    return kwargs

然后我将额外的文章(pk)添加到 init

forms.py

def __init__(self, user=None, pk=None, **kwargs):
    super(FileUploadForm, self).__init__(**kwargs)
    if user:
        self.fields['category'].queryset = Category.objects.filter(user=user, parent_id=pk)

1 个答案:

答案 0 :(得分:1)

您的表单需要user参数,但您没有提供参数,因此user始终为None。您可以覆盖视图get_form_kwargs method以将用户传递到表单:

class AddDocumentView(LoginRequiredMixin, SuccessMessageMixin, CreateView):

    def get_form_kwargs(self):
        kwargs = super(AddDocumentView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

您的FileUploadForm现在将获取用户对象,并会相应地过滤结果。