【问题标题】:Django retain form data after GET requestDjango在GET请求后保留表单数据
【发布时间】:2015-07-02 02:21:00
【问题描述】:

如何保留在基于类视图的表单中输入的数据?

class SearchView(FormMixin, ListView):
    # formview stuff

    form_class = SearchForm
    template_name = 'search.html'
    context_object_name = 'spaces'
    # listview stuff
    def get_queryset(self):
            spaces = Space.objects.all()
            location = self.request.GET.get('location', '')
            radius = self.request.GET.get('radius', 2.0)
            space_size = self.request.GET.get('size')
            # chain all filters below
            if location and radius:
                    # create a geo POINT from location entry
                    geocoder = GoogleV3()
                    latlon = geocoder.geocode(location)
                    latilongi = latlon[1]
                    latitude, longitude = latilongi
                    current_point = geos.fromstr("POINT({0} {1})".format(longitude, latitude))
                    # get search radius from get request
                    distance_from_point = float(radius)
                    spaces = Space.objects.all()
                    spaces = spaces.filter(location__distance_lte=(current_point, measure.D(mi=distance_from_point)))
            if space_size:
                    spaces = spaces.filter(size__gte=space_size)

            if not spaces:
                    return None # return all objects if no radius or space.
            else:
                    return spaces

    def get_context_data(self, **kwargs):
            context = super(SearchView, self).get_context_data(**kwargs)
            context['form'] = self.get_form()
            return context

每个 get 请求都给我一个空表单,但是将数据保留在表单中的最佳方法是什么?这是一个搜索页面,所以它返回你的结果有点奇怪,但你看不到你的查询是什么。

使用函数视图可以很容易地保留表单,但我想使用 CBV。

谢谢

【问题讨论】:

    标签: django django-class-based-views


    【解决方案1】:

    get_initial() 应该为您提供生成表单的初始数据:

    def get_initial(self):
        return {
            'location': self.request.GET.get('location', ''),
            'radius': self.request.GET.get('radius', 2.0),
            'space_size': self.request.GET.get('size'),
        }
    

    【讨论】:

    • 嗯,这似乎应该工作,但它没有返回任何东西。即使我将这些值设置为字符串,而不是尝试从请求中获取它们,它们仍然是空的。是否也与上下文中的表单有关,这似乎覆盖了表单类 + formmixin?
    • 对,似乎它必须在其他方法之上,直接在 context_object_name 之下,而不是在其他方法之后。谢谢
    • 这很奇怪,方法顺序在 Python 中应该无关紧要。难道你不小心把它放在了我们的班级里吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 2015-07-01
    相关资源
    最近更新 更多