Django的GET形式ListView和上下文修改 [英] Django GET form in ListView and context modification

查看:371
本文介绍了Django的GET形式ListView和上下文修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从的ListView 导出一个通用的基于类的视图。该视图应在 forms.py 声明的形式通过GET查询过滤objects_list,同时,也修改上下文进行交互(如果你有兴趣,为什么我倒要做到这一点,检查我的<一个href=\"http://stackoverflow.com/questions/33699897/django-best-practices-should-i-use-a-listview-or-a-normal-view-if-i-want-to-dis\">$p$pvious问题)。

I have a generic class-based view derived from ListView. The view should interact with a form declared in forms.py to filter the objects_list via a GET query and, also, modify the context (if you're interested in why I'd like to do that, check my previous question).

这意味着我需要形式的实例( =形式的MyForm(request.GET中))无论是在 get_queryset get_context_data 方法。

This means I need an instance of the form (form = MyForm(request.GET)) both in the get_queryset and get_context_data methods.

<一个href=\"http://stackoverflow.com/questions/7295886/django-listview-specifying-variable-available-for-all-methods-inside-the-class\">This解决方案是不能接受的,因为这是违反了<一个href=\"http://stackoverflow.com/questions/19284857/instance-attribute-attribute-name-defined-outside-init\">this编码原则,假设 get_queryset 总是被首先调用(这可能不是在Django的未来版本的情况下)。

This solution is not acceptable since it is a violation of this coding principle and assumes that get_queryset will always gets called first (which may not be the case in future versions of Django).

例如:

def get_queryset(self):
    self.form = MyForm(self.request.GET)


将该溶液是不能接受的,因为它使用的原始的GET参数,而我们想利用的形式自动解析/验证的全部潜力。


This solution is not acceptable since it uses the raw GET arguments while we'd like to harness the full potential of the form automatic parsing/validation.

例如:

def get_queryset(self):
    a_form_field = self.kwargs["a_form_field"]

这是可以做到不违反任何好的设计原则?

Is this possible to do without violating any good design principle?

推荐答案

我会重写 GET 方法:

class SearchList(ListView):
    def get(self, request, *args, **kwargs):
        self.form = MyForm(request.GET)
        if self.form.is_valid():
            self.queryset = self.form.process_search(self.queryset)

        return super(SearchList, self).get(request, *args, **kwargs)

您的形式需要有 process_search 来保存查询集过滤流量(这种方式你保持窗体类里面搜索登录)。

Your form will need to have process_search to hold the queryset filtering flow (this way you keep the search login inside form class).

您可以访问 self.form 之后,你可以用 {{} view.form} 。

You can access self.form afterwards and you can access it inside template with {{ view.form }}.

这篇关于Django的GET形式ListView和上下文修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆