【发布时间】: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