Working with URL, GET, POST parameters in Django

(Comments)

This tutorial tries to clarify on how one can pass parameters from one page to another page in Django.

I follow three ways:

1. Parameters as part of url
2. GET parameters
3. POST parameters

1. Parameters as part of url:

In general sense, if we want to display a list of users, the proper url can be:

/users

If we want to display the details of a particular user with id 5, proper url will be like:

/users/5

This can be achieved by setting url like this

url(r'^users/(?P<user_id>\d+)/$', 'viewname', name='urlname')

If you observe well, we have used user_id in the above link. This url says that the url is expecting a parameter user_id of type number. In regex, \d is [0-9]. This user_id is passed to the view as a parameter.

def viewname(request, user_id):
    user = User.objects.get(id=user_id)
    #do something with this user

In class based view, we can get url parameter in kwargs

class SampleView(TemplateView):
    def get_context_data(self, **kwargs):
        user = User.objects.get(id=kwargs['user_id'])
        #do something with this user

2. GET parameters

First have a look at this url. One place where we use GET parameters is filters.

/products?price_lte=5000

For this kind of url, we need not specify any regex for price_lte(parameter). Url can be:

url(r'^products/$', 'viewname', name='urlname')

def viewname(request):
    price_lte = request.GET['price_lte']
    #Code to filter products whose price is less than price_lte i.e. 5000

3. POST parameters

In general case, url when sending post parameters doesnt contain anything related to parameters in the url. For example:

/register

Urls.py will contain something like

url(r'^register/$', 'register', name='urlname')

The corresponding view will be:

def register(request):
    form = RegisterForm()
    if request.method == "POST":
        form = RegisterForm(request.POST) #if no files
        if form.is_valid():
            #do something if form is valid
    context = {
        'form': form
    }
    return render(request, "template.html", context)

The above view is actually rendering the empty form on every GET request i.e. when the page is opened. On POST request, if the form is valid, it usually saves the form during the registration. If the form is invalid, it will simply render the form again with entered values and errors.

The form for the above view will be like:

{{ form.as_p }} #in template

which renders the form html.

All the html input elements having attribute name will be sent as POST parameters on submit. In POST parameters, value of name of that element will be sent as key and the value of that html element will be sent as value to the key.

For the html elements:

<input type='text' name='num' value=5 />

In view:

request.POST['num']  # returns 5

Comments

Recent Posts

Archive

2021
2020
2019
2018
2017
2016
2015
2014

Tags

Authors

Feeds

RSS / Atom