Get parameters passed by urls in Django
Django is a fully fleshed framework which can help you create web applications of any form. This article discusses how to get parameters passed by URLs in django views in order to handle the function for the same. You might have seen various blogs serving with urls like: –
In the url above 991 is the Id of article which is being currently served to you. We are going to make this functionality in Django.
- Create an new virtual environment and install Django.
- Start a new Django project by typing this command: –
django-admin startproject test
- Create a very simple Article model in your models.py.
- Now go to django admin and add some articles for testing.
Now open your urls.py file and add the url pattern as given below: –
Make sure to import your views.py file here.
The <id> here will help us get and use the id parameter in our view.
Now create a new views.py file and add the following view: –
Make sure to replace your_template with your template path. Now you should be able to access article inside your template and render it.
Visit http://localhost:8000/articles/1 in your browser and you will be able to see your article. If you replace 1 with any non-existent id it will show a 404 not found error.