Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Get the Current URL within a Django Template
Next article icon

Get the Current URL within a Django Template

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Django, a high-level Python web framework, encourages rapid development and clean, pragmatic design. One common requirement when developing web applications is to access the current URL within a template. This can be useful for various purposes such as highlighting the active link in a navigation menu or generating dynamic content based on the URL.

In this article, we will walk you through the steps to create a Django project and demonstrate how to get the current URL within a Django template.

Here are a few useful attributes of the request object that we will use:

  • {{ request.path }}: The path of the current URL without the domain.
  • {{ request.build_absolute_uri }}: The full URL including the domain.

Get the Current URL within a Django Template

Before we dive into fetching the current URL within a template, let's first set up a basic Django project. If you haven't installed Django yet, you can do so by running

pip install django

Step 1: Start a New Django Project

Open your terminal and run the following command to start a new Django project named myproject:

django-admin startproject myproject

Navigate into the project directory:

cd myproject

Step 2: Create a Django App

Next, create a new app within the project. We'll name it myapp:

python manage.py startapp myapp

Add the new app to the INSTALLED_APPS list in myproject/settings.py:

INSTALLED_APPS = [
...
'myapp',
]
f1


Step 3: Create a View

In myapp/views.py, create a simple view for the home page and about page:

Python
from django.shortcuts import render  def home(request):     return render(request, 'home.html')  def about(request):     return render(request, 'about.html') 

Step 4: Create a Template

Create a directory named templates within the myapp directory, and inside it, create a file named home.html and about.html. In the example above, we use {{ request.get_full_path }} within the home.html template. This expression will output the current URL, including the query string if any.

home.html

HTML
<!DOCTYPE html> <html> <head>     <title>Home Page</title> </head> <body>     <h1>Welcome to MyApp</h1>     <p>The current URL is: {{ request.get_full_path }}</p>     <a href="{% url 'about' %}">About</a> </body> </html> 

about.html

HTML
<!DOCTYPE html> <html> <head>     <title>About Page</title> </head> <body>     <h1>About MyApp</h1>     <p>The current URL is: {{ request.get_full_path }}</p>     <a href="{% url 'home' %}">Home</a> </body> </html> 

Step 5: Define a URL Pattern

Open myproject/urls.py and include the URL patterns for myapp:

Python
from django.contrib import admin from django.urls import path, include  urlpatterns = [     path('admin/', admin.site.urls),     path('', include('myapp.urls')), ] 

Now, create a urls.py file within the myapp directory and define a simple URL pattern:

Python
from django.urls import path from . import views  urlpatterns = [     path('', views.home, name='home'),     path('about/', views.about, name='about'), ] 

Run the Server

run the server using the below command

python manage.py runserver

navigate the http://127.0.0.1:8000/ in web browser

Output

2
1

Conclusion

Accessing the current URL within a Django template is straightforward once you have the request object available. By configuring the request context processor, you can easily retrieve various attributes of the current request, including the URL, and use them within your templates to create dynamic and responsive web applications.


Next Article
Get the Current URL within a Django Template

P

prathamsahani0368
Improve
Article Tags :
  • Python
  • Python Django
  • Django-templates
Practice Tags :
  • python

Similar Reads

    Display the Current Year in a Django Template
    In this simple project, we demonstrated how to display the current year in a Django template. By using the datetime module in Python, we passed the current year to the template context, which allowed us to display it in the HTML. This method can be applied to various dynamic content needs in Django
    2 min read
    Get the Absolute URL with Domain in Django
    When developing web applications, generating the full URL (including the domain) is often necessary. For instance, sending confirmation emails with links, generating sitemaps, or creating social media share links require absolute URLs. Django provides several utilities and methods to achieve this se
    3 min read
    How to Read the Current full URL with React?
    In React applications, it is often necessary to read the current full URL for various purposes, such as routing, conditional rendering, or logging. There are two common approaches to achieve this: using the window.location object and using the useLocation hook from react-router-dom. Prerequisites:NP
    3 min read
    url - Django Template Tag
    A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
    3 min read
    Get the current URL using jQuery
    The current URL in jQuery can be obtained by using the 'href' property of the Location object which contains information about the current URL. The href property returns a string with the full URL of the current page. We can access the value of the href property using two different methods of jQuery
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences