【问题标题】:How to filter select values using foreign keys in Django form如何在 Django 表单中使用外键过滤选择值
【发布时间】:2016-09-19 20:04:44
【问题描述】:

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

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

然后我将额外的 agument(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)

【问题讨论】:

    标签: python django django-forms django-views


    【解决方案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 现在将获取用户对象并相应地过滤结果。

    【讨论】:

    • 效果很好,谢谢。我会以同样的方式传递 parent_id 吗?
    • 不知道parent_id是什么?如果这是您的视图知道的事情,那么是的。
    • 谢谢,我想通了。 parent_id 是 URL 中的主键,所以我使用“kwargs['pk'] = self.kwargs['pk'] 并修改 init 以接受它作为参数。我会发布即将更新的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 2016-07-12
    • 2019-07-23
    • 1970-01-01
    • 2016-06-24
    • 2020-01-28
    • 2011-03-14
    • 1970-01-01
    相关资源
    最近更新 更多