Django 在 GET 请求后保留表单数据
Django retain form data after GET request
如何保留在具有 Class 基于视图的表单中输入的数据?
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 请求都会给我一个空表单,但是将数据保留在表单中的最佳方式是什么?这是一个搜索页面,returns 你的结果有点奇怪,但你看不到你的查询是什么。
使用函数视图很容易保留表单,但我想使用 CBV。
谢谢
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'),
}
如何保留在具有 Class 基于视图的表单中输入的数据?
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 请求都会给我一个空表单,但是将数据保留在表单中的最佳方式是什么?这是一个搜索页面,returns 你的结果有点奇怪,但你看不到你的查询是什么。
使用函数视图很容易保留表单,但我想使用 CBV。
谢谢
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'),
}