使用表单后修改上下文

时间:2015-03-29 14:23:53

标签: python django django-forms django-views

我的视图显示了具有特定标记的对象列表。

class AllView(ListView):

    context_object_name = 'facts'
    template_name = 'facts_blog/all_facts.html'

    def get_context_data(self, **kwargs):
        context = super(AllView, self).get_context_data(**kwargs)
        if 'TagForm' not in context:
            context['TagForm'] = TagForm()
        return context

    def get_queryset(self):
        form = TagForm(self.request.GET)
        if form.is_valid():
            context = RequestContext(self.request)
            return self.send_results(form.cleaned_data['tag'])
        else:
            return Fact.objects.all()

    def send_results(self, tag):
        return Fact.objects.filter(tags__slug=tag)

我想将form.cleaned_data [' tag']返回给模板,但我已经使用了get_context_data ...我该怎么办呢?

2 个答案:

答案 0 :(得分:0)

如果我理解您所说的内容,您希望包含"标记"在你的上下文dict中,ListView查询集将返回"事实"与标记关联的实例。正确的吗?

如果您查看Django的BaseListViewget方法会先调用get_queryset,然后在调用render_to_response之前调用get_context_data class BaseListView(MultipleObjectMixin, View): """ A base view for displaying a list of objects. """ def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() # [snip] # some code not related to this omitted # [snip] context = self.get_context_data() return self.render_to_response(context) 方法:

self.object

您可以在get_queryset方法中设置属性(get_context_data)来存储"标记"从您的验证表单中,然后在您的def get_queryset(self): form = TagForm(self.request.GET) if form.is_valid(): context = RequestContext(self.request) # set self.object to the "tag" self.object = form.cleaned_data['tag'] return self.send_results(self.object) else: # set self.object to None since the form is not validated self.object = None return Fact.objects.all() def get_context_data(self, **kwargs): context = super(AllView, self).get_context_data(**kwargs) if 'TagForm' not in context: context['TagForm'] = TagForm() # put self.object in the context dict context['tag'] = self.object return context 方法中检索它,以便您可以将其填充到上下文中:

tag

您的模板将有一个名为None的变量,其中包含"标记"价值或{{1}}。

答案 1 :(得分:0)

假设表单的操作通过GET请求返回到AllView视图,您可以用这种方式修改get_context_data

def get_context_data(self, **kwargs):
    context = super(AllView, self).get_context_data(**kwargs)
    if 'TagForm' not in context:
        context['TagForm'] = TagForm()

    tag_form = TagForm(self.request.GET)
    if tag_form.is_valid():
        context['tag'] = tag_form.cleaned_data.get('tag')

    return context

希望它成功。