Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access request variable in Django CreateView form_valid method

How do I access request in form_valid ?

def redirect_logic_func(request):
   #redirect logic

class CView(CreateView):
    form_class = CForm
    template_name = "c_form.html"

    def form_valid(self, form):
        form.save()
        super(CView, self).form_valid(form)
        return redirect_logic_func(self.request)

Is self.request.POST the same as request.POST ?

like image 375
hlkstuv_23900 Avatar asked Dec 04 '22 02:12

hlkstuv_23900


1 Answers

  1. To access the request variable in form_valid(), you just need to use self.request. This will provide you with the request variable.
  2. No, there is no need to override the .post() to access the request variable in form_valid().
  3. Yes, self.request.POST is the same as request.POST as they are the same request object.

So, your final code should look like:

def redirect_logic_func(request):
   #redirect logic

class CView(CreateView):
    form_class = CForm
    template_name = "c_form.html"

    def form_valid(self, form):
        form.save()
        super(CView, self).form_valid(form)
        return redirect_logic_func(self.request) # use self.request
like image 170
Rahul Gupta Avatar answered Dec 28 '22 06:12

Rahul Gupta