GET & POST in Django Made Easy

5/5 - (1 vote)

I’m currently working on the Finxter app that I implemented using Python and Django. When slightly modifying the submit form that used a "POST" HTTP method I wondered if this would be also possible with HTTP "GET". And what is the technical difference anyway? ๐Ÿง‘โ€๐Ÿ’ป

In this article, I quickly condense my research in case you had a similar question. Let’s get started! ๐Ÿ‘‡

GET: The Data Gatherer ๐Ÿ“š

The GET method is your data retriever, your information scout.

Whenever youโ€™re visiting a website by typing that URL in your browser, you’re sending a GET request to the server. In Django-land, you’ll check for a GET request with request.method == 'GET'.

Here’s the deal with GET: It carries request parameters in the URL.

That means your parameters are visible in the browser and stay in the browser history. It’s like airing your laundryโ€” everyone can see it!

So, donโ€™t use GET to transmit sensitive data, alright? Oh, and remember it’s also got a length limit.

POST: The Data Courier ๐Ÿ“ฎ

Now meet POST, the method that delivers data to the server. Think of it as your data courier.

Itโ€™s used when you’re sending data to the server for processing, like when submitting a form. You check for a POST request in Django with request.method == 'POST'.

Unlike our friend GET, POST is a master of disguise ๐Ÿ•ต๏ธโ€โ™‚๏ธ. It sends data in the body of the request, making it a secure choice for transmitting sensitive info. POST doesnโ€™t leave traces in the browser history or get cached, and there’s no limit on the data length.

GET and POST: The Form Handlers ๐Ÿ“

These two methods really shine when dealing with HTML forms.

When you load a form on a webpage, youโ€™re typically fetching it using a GET request. But when you hit that “Submit” button, if the form is set to "POST", your browser whisks off a POST request to the server with the form data neatly packaged in the request’s body.

Here’s a snapshot of a POST form:

<form action="/submit_data" method="post">
    <input type="text" name="data">
    <input type="submit" value="Submit">

But remember, forms can use GET too.

<!-- Using GET -->
<form action="/search" method="get">
    <input type="text" name="q">
    <input type="submit" value="Search">

<!-- Using POST -->
<form action="/login" method="post">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" value="Log in">

In those cases, the form data will join the URL party. It’s ideal for something like search forms where you arenโ€™t changing server data and donโ€™t mind sharing the request URL.

Keep coding, and see you on the server side! ๐Ÿ˜‰

๐Ÿง‘โ€๐Ÿ’ป Recommended Tutorial: How I Created an URL Shortener App Using Django