user963936
user963936

Reputation: 669

Add query string to url in Django

I have a form which sends a POST request and returns a page. The url of this page is defined like this

(r'^result/', 'main.views.eval_form'),

and in the browser the url looks like

mysite.com/main/result

But I also have the url working with a Get Request so the user could save the url and not have to use the form, ie:

mysite.com/main/result?name=Tom&color=blue&etc=etc

Now is there a way to alter the url in the browser after the user uses the form, to include the query string by default? So that the user can copy the url and always return to result?

Thank you!

Upvotes: 0

Views: 844

Answers (3)

Koed00
Koed00

Reputation: 671

You could do a HttpResponseRedirect to the url with the prefilled querystring from the Post view. Make sure you don't submit it twice or create an infinite loop.

return HttpResponseRedirect("/result?name={}&color={}&etc={}".format(name, color, etc))

Another way would be to fill your querystring with jQuery or Javascript from the template.

Myself I would take catavaran's approach

Upvotes: 1

Tong Liu
Tong Liu

Reputation: 46

If you want to achieve this, you should alter your view to deal with both post and get request.

code may be like this:

def result(request):
    name = request.REQUEST.get("name")

but request.REQUEST is deprecated since django 1.7

def result(request):
    if request.method == "GET":
        name = request.GET.get("name")
    if request.method == "POST":
        name = request.POST.get("name")

Upvotes: 0

catavaran
catavaran

Reputation: 45575

Change the method attribute of the <form> tag:

<form action="/main/result/" method="GET">
    ...
</form>

Upvotes: 1

Related Questions