我必须指定一个success_url
,否则我会收到错误。那么如何指定它,以便保持同一页面?
此外,关于SearchView,其他一切都是正确的,因为我觉得缺少某些东西。我的上下文应由form
,query
,concepts
,language
和languages
组成。
感谢
urls.py
url(r'^(?P<langcode>[a-zA-Z-]+)/search/$', SearchView.as_view(), name='search').
views.py
class _LanguageMixin(object):
def dispatch(self, request, *args, **kwargs):
self.langcode = kwargs.pop("langcode")
self.language = get_object_or_404(Language, pk=self.langcode)
return super(_LanguageMixin, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(_LanguageMixin, self).get_context_data(**kwargs)
context.update({"language": self.language,
"languages": Language.objects.values_list('code',
flat=True)})
return context
class SearchView(_LanguageMixin, FormView):
template_name = "search.html"
form_class = SearchForm
success_url = #......
query = ''
concepts = []
def get_initial(self):
return {'langcode': self.langcode}
def get_context_data(self, **kwargs):
context = super(SearchView, self).get_context_data(**kwargs)
context.update({"query": self.query, "concepts": self.concepts})
return context
def form_valid(self, form):
self.query = form.cleaned_data['query']
self.concepts = # here is a long DB query; function(query)
return super(SearchView, self).form_valid(form)
[编辑] 我这样做了:
def get_success_url(self):
return reverse('search', kwargs={'langcode': self.langcode})+"?query={}".format(self.query)
表单呈现,但每当我搜索任何内容时,我都会返回空的搜索文本字段。 URL看起来像这样:http://localhost:8000/en-US/search/?query=asd
答案 0 :(得分:2)
默认情况下,FormView
(实际上是ProcessFormView
的任何子类)将在HttpResponseRedirect
中返回form_valid
。当您在super
方法中调用form_valid
方法时,您还会返回HttpResponseRedirect
。在此过程中,实际的POST
数据会丢失,虽然您将其作为GET
参数传递,但它并未在实际表单中使用。
要解决此问题,您无需在super
方法中调用form_valid
,而是在HttpResponse
对象中返回呈现的模板,例如:
def form_valid(self, form):
self.query = form.cleaned_data['query']
self.concepts = # here is a long DB query; function(query)
return self.render_to_response(self.get_context_data(form=form))