Open In App

Get parameters passed by urls in Django

Last Updated : 18 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • 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.

python3




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


  • Now go to django admin and add some articles for testing.

Creating Url

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

python3




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

python3




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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads