Saqib Ali
Saqib Ali

Reputation: 12585

How to make a Django view that does both a GET and POST?

I am creating instances of my Django model object: myObject.

I have already setup a Django Form Wizard to allow the user to create new instances of myObjects.

I have already setup a view that allows the user to "drilldown" on myObject using a GET like this: "myWebsite.com/?objID=5"

After the last step of the Form Wizard, I redirect the user to "myWebsite.com/?objID=" So far so good. It works. However I have two new requirements:

  1. At the top of this drilldown page, I want it to say "Here is your newly created Object" if I was just redirected to this page by the Form Wizard.
  2. Regardless of weather I came to this drilldown page from the Form Wizard or by any other means, I want the URL to remain the same as I have explained above.

Requirement #2 Necessitates that I use a POST so as not to change the URL. But the original URL requires a GET. So it seems I need to do a GET and a POST on the same page. How can I do that? Am I misunderstanding something? Is there a better way for me to accomplish what I'm trying to do?

Upvotes: 2

Views: 5539

Answers (4)

max
max

Reputation: 10454

Here is what I use:

# views.py
def api(request):
    params = request.POST.copy()
    params.update(request.GET)
    # now params has both get and post params merged

Upvotes: 2

Aidan Ewen
Aidan Ewen

Reputation: 13308

You can't make an http request that is both a POST and a GET request. Trying to do so is bad and will break the interweb.

It goes against RFC2616 (the w3c specification for http). http provides for a single method which must be one of 'OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT'

Although this is a principle often ignored by developers, GET is designed to retrieve a resource from a server, specifically, without changing the state of that, or any, resource on the server. Conversely, a POST request is specifically for changing the state of a resource. So GET is for Query's and POST is for database changes.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599630

You don't actually need to make both GET and POST requests simultaneously. What you're missing is that a POST request can actually have GET parameters as well as POST ones. So, as matino points out in the comments, this is perfectly valid:

<form method="POST" action="myWebsite.com/?objID=5">

In your view, request.GET will contain {'objID': 5} and request.POST will contain whatever is submitted in your form.

Upvotes: 3

Rohan
Rohan

Reputation: 53336

request.method tells you what http method is used for a request in the view. So you can code it accordingly.

e.g.

def my_view(request):

    if request.method == 'GET':
        #do processing for get

    else if request.method == 'POST':
        #do processing for POST

    ...

Upvotes: 0

Related Questions