Djang在GET请求后保留表单数据

时间:2015-04-23 18:10:09

标签: django django-class-based-views

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

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。

由于

1 个答案:

答案 0 :(得分: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'),
    }