Mahmoud Adel
Mahmoud Adel

Reputation: 1330

Why check if the request is POST in Django views.py?

I'm a beginner in Django so while learning I found something.

Some people are doing a request check for example:

def register(request):
    if request.method =='POST':
        # Register user
        redirect()
    else:
        return render(request,'accounts/register.html')

So I found it unnecessary because the action and method are already specified it in my HTML form.

<form action="{% url 'register' %}" method="POST">

So for me, it makes no sense, as we only making a post a request to register.

Am I wrong?

Upvotes: 6

Views: 14801

Answers (2)

Sanip
Sanip

Reputation: 1810

Post requests are made to submit any user input to the server backend. To simply state your query, this is a basic flow of a web program:

  1. Whenever a user visits a site by entering the url(https://example.com), then a GET request is submitted to the server as GET / [status_code]. So, even if the template in the requested url contains a 'POST' form, first a GET request is to be made.
  2. Now if the user fills a form and submits the data using POST method, server gets a request as POST / [status_code].

Hence, to handle both types of requests, you need to check the request method that is being made. I think I have answered your query.

Upvotes: 3

ruddra
ruddra

Reputation: 51998

Here you are using view for both GET and POST requests. More explanation is given in the code below:

def register(request):
    if request.method =='POST':  # comes here when you are making a post request via submitting the form
        # Register user
        redirect()
    else:  # if you are making a get request, then code goes to this block
        return render(request,'accounts/register.html')  # this is for rendering the html page when you hit the url

Upvotes: 7

Related Questions