Open In App

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: – 

www.example.com/articles/991 



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.

Project Setup

django-admin startproject test




class Article(models.Model):
    author = models.CharField(max_length = 20)
    content = models.TextField()

Creating Url

Now open your urls.py file and add the url pattern as given below: –






url_patterns += [
    path("articles/<id>/", views.article_detail, name ="article_detail"),
]

Make sure to import your views.py file here.

The <id> here will help us get and use the id parameter in our view.

Writing View

Now create a new views.py file and add the following view: –




def article_detail(request, id):
  article = Article.objects.filter(id = id)
  return render("your_template", context ={"article":article})

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.


Article Tags :