Django - FormView结合Mixin

时间:2014-05-19 14:54:55

标签: django django-forms mixins django-class-based-views class-based-views

我必须指定一个success_url,否则我会收到错误。那么如何指定它,以便保持同一页面? 此外,关于SearchView,其他一切都是正确的,因为我觉得缺少某些东西。我的上下文应由formqueryconceptslanguagelanguages组成。 感谢

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

1 个答案:

答案 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))