How to process a form (via get or post) using class-based views?

前端 未结 2 1303
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 01:26

Im trying to learn class-based views, for a detail or list view is not that complicated.

I have a search form and I just want to see if I send a query to show up the res

2条回答
  •  孤城傲影
    2021-01-30 01:55

    Note, an answer here (Updating context data in FormView form_valid method?) solved this problem like this:

    class ContextFormView(FormView):
        template_name = 'some_template.html'
        success_url = '...'
        form_class = ClassOfTheForm
    
        def get(self, request, *args, **kwargs):
            form_class = self.get_form_class()
            form = self.get_form(form_class)
            context = self.get_context_data(**kwargs)
            context['form'] = form
            return self.render_to_response(context)
    
        def post(self, request, *args, **kwargs):
            form_class = self.get_form_class()
            form = self.get_form(form_class)
            if form.is_valid():
                return self.form_valid(form, **kwargs)
            else:
                return self.form_invalid(form, **kwargs)
    
    
        def form_invalid(self, form, **kwargs):
            context = self.get_context_data(**kwargs)
            context['form'] = form
            # here you can add things like:
            context[show_results] = False
            return self.render_to_response(context)
    
        def form_valid(self, form, **kwargs):
            context = self.get_context_data(**kwargs)
            context['form'] = form
            # here you can add things like:
            context[show_results] = True
            return self.render_to_response(context)
    

    This worked perfect for me. (same issue as in this question)

    As stated above, this is not my solution, if you want to give somebody credits, go to the answer in the link and give this person the credits! (Updating context data in FormView form_valid method?)

提交回复
热议问题