djangodjango-views

How can I change the http request from Post to Get in Django?


Suppose I have a view which will take a POST request. After the validation check pass, I need to redirect the request to another HTML/view with a request with GET method:

def view1(request):
    if request.POST:
       form = TempForm(request.POST)
       if form.is_valid():
           return redirect(request, 'view2')

def view2(request):
    if request.POST:
       #POST stuff here
    else:
       #GET stuff here

My problem is that after the form.is_valid(), the redirect request will be passed as a POST method. My ultimate goal is to redirect the view2 with GET method.

Can I do such thing in Django?


Solution

  • You can use an HttpResponseRedirect class to redirect to any URL you like. Since it's a redirect, the request will be a GET request (POST isn't possible with http redirect - that's a restriction of the http protocol).

    If you need to add GET parameters you could simply create the GET string yourself -

    get_string = "?"
    get_strint += "my_param=" + my_variable + "&"
    get_string += "my_other_param=" + my_other_variable
    return HttpResponseRedirect('/my_url/' + get_string)