django表单查询集由当前用户过滤

时间:2014-06-26 06:18:29

标签: django forms

我已经制作了一个这样的搜索表单,用户可以根据发布的日期和之前选择的抓取工具过滤新闻。这是我的表单

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.filter(created_by=self.request.user)

这里我希望只显示用户之前选择过的抓取工具..

这是我的观点..

class SingleNewsView(ListView):
model = News
form_class = SearchForm
template_name = "single_news.html"

# def post(self, request, **kwargs):
#   print "request"
#   form = SearchForm(request.user)



def get(self, request, pk, **kwargs):

    #form = SearchForm(request.user)
    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
    if self.pub_from and self.pub_to and self.crawlers:
        qs = News.objects.filter(category_id=self.pk).filter(published_date__range=(self.pub_from,self.pub_to), crawler=self.crawlers)
    else:
        qs = News.objects.filter(category_id=self.pk)

    context["something"] = qs
    self.request.session['something_pks'] = [ i.details for i in qs ]

    return context

如何根据当前用户获取当前用户的表格并进行过滤..需要帮助

2 个答案:

答案 0 :(得分:0)

只需将用户作为关键字参数传递给视图。

只是不要在表单init方法中传递它。看看这篇文章:

Passing **kwargs to Django Form

你移交request.user,就像user_details在该例子中传递给表单一样。

答案 1 :(得分:0)

# Your best option is to declare the variable before `__init__`, 
# and then set the variable to a form field inside `__init__`:

from django import forms


class MyForm(forms.Form):
    location = None

    def __init__(self, *args, **kwargs):
        self.location = forms.ChoiceField(choices=Locations.objects.filter(user=kwargs.pop('user', None)))

        super(MyForm, self).__init__(*args, **kwargs)


# In your class-based view pass self.request.user
# or in a function-based view pass request.user:
def MyView(request)
    MyForm(user=request.user)