我写了一个这样的表单,我只想显示当前用户选择的抓取工具。我的表单看起来像
class SearchForm(forms.Form):
pub_date_from = forms.CharField(label="From",max_length=20)
pub_date_to = forms.CharField(label="To",max_length=30)
crawler = forms.ModelMultipleChoiceField(label="Crawler",queryset=Crawler.objects.all())
这里我列出了所有抓取工具,但我只想要当前用户选择的抓取工具。我使用它作为搜索表单,他只能从他之前选择的爬虫中搜索。我怎样才能做到这一点。我已将此表单用作搜索的上下文。
我的观点看起来像这样..
class SingleNewsView(ListView):
model = News
form_class = SearchForm
template_name = "single_news.html"
def get(self, request, pk, **kwargs):
self.pk = pk
self.pub_from = request.GET.get('pub_date_from',False)
self.pub_to = request.GET.get('pub_date_to',False)
self.crawlers = request.GET.get('crawler',False)
self.format = request.GET.get('format',False)
print self.format
print self.crawlers
return super(SingleNewsView,self).get(request,pk, **kwargs)
def get_context_data(self, **kwargs):
context = super(SingleNewsView,self).get_context_data(**kwargs)
context["form"] = SearchForm#(self.request.GET)
if self.pub_from and self.pub_to and self.crawlers:
context["something"] = News.objects.filter(category_id=self.pk).filter(published_date__range=(self.pub_from,self.pub_to), crawler=self.crawlers)
else:
context["something"] = News.objects.filter(category_id=self.pk)
return context
任何人都可以告诉我如何才能获得当前用户选择的抓取工具。
答案 0 :(得分:1)
当您实例化表单时,您必须传入要用于选择的对象,您可以在视图中使用:self.request.user.crawler_set.all()
。然后我想你可以传入对象并将它们设置为__init__
形式的字段选择。
所以你的搜索表格看起来与此相似..
class SearchForm(forms.Form):
pub_date_from = forms.CharField(label="From",max_length=20)
pub_date_to = forms.CharField(label="To",max_length=30)
crawler = forms.ModelMultipleChoiceField(label="Crawler",queryset=Crawler.objects.all())
def __init__(self, user, *args, **kwargs):
if user:
self.fields['crawler'].queryset = user.crawler_set.all()
您将在视图中使用以下内容实例化表单:
context["form"] = SearchForm(self.request.user, instance=self.request.GET)