Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Get parameters passed by urls in Django
Next article icon

In Django, views are Python functions that handle HTTP requests. These views process the request and return an HTTP response or an error (e.g., 404 if not found). Each view must be mapped to a specific URL pattern. This mapping is managed through URLConf (URL Configuration).

In this article, we'll explore how URL patterns are used in Django, how they are defined in urls.py, and how different URL patterns help in routing requests to appropriate views.

Understanding URLConf in Django

In Django, the URLConf refers to the process of mapping URLs to views. This mapping is defined in a Python module, usually called urls.py. The configuration module specified in the ROOT_URLCONF setting in settings.py determines which module is used for URL mapping.

For a project named myProject, the default ROOT_URLCONF is typically set to 'myProject.urls'. Every URLConf module contains a variable urlpatterns, which is a list or set of URL patterns that Django checks against the requested URL. The patterns are checked in sequence, and when a match is found, the corresponding view is invoked. If no match is found, Django triggers an appropriate error handling view.

Structure of URLConf in Django:

Python
# myProject/urls.pyfromdjango.contribimportadminfromdjango.urlsimportpath,includeurlpatterns=[path('admin/',admin.site.urls),path('',include('books.urls')),# Including URL patterns from the books app]

In the above example:

  • path('admin/', admin.site.urls) maps the URL /admin/ to Django's default admin interface.
  • path('', include('books.urls')) tells Django to look for additional URL patterns in the books.urls module, which is typically located in the books app.

URL Patterns in Django

URL patterns are defined inside the urlpatterns list. This list contains the routes Django uses to match incoming URLs to appropriate views.

Here is a sample urls.py for the books app:

Python
# books/urls.pyfromdjango.urlsimportpathfrom.importviewsurlpatterns=[path('books/<int:pk>/',views.book_detail),# Detail view for a book, identified by primary key (pk)path('books/<str:genre>/',views.books_by_genre),# View books by genrepath('books/',views.book_index),# List all books]

Explanation:

  • path('books/<int:pk>/', views.book_detail):This pattern matches /books/25/, where 25 is an integer representing the primary key (PK) of a book. Django will call views.book_detail(request, pk=25).
  • path('books/<str:genre>/', views.books_by_genre):This pattern matches /books/crime/, where crime is a string representing the genre of books. Django will call views.books_by_genre(request, genre="crime").
  • path('books/', views.book_index):This pattern matches /books/, which lists all books. Django will call views.book_index(request).

Example: How Django URLs Work — Basic HTML Pages & Navigation

1. Define views in views.py:

Python
fromdjango.httpimportHttpResponsefromdjango.shortcutsimportrenderdefhome_view(request):returnrender(request,'home.html')defabout_view(request):returnrender(request,'about.html')defcontact_view(request):returnrender(request,'contact.html')

2. Create basic templates in your templates/ folder:

home.html:

HTML
<h1>Home Page</h1><p>Welcome to the home page.</p><ahref="/about/">Go to About</a><br><ahref="/contact/">Go to Contact</a>

about.html:

Python
<h1>AboutPage</h1><p>Thisistheaboutpage.</p><ahref="/">GotoHome</a><br><ahref="/contact/">GotoContact</a>

contact.html:

HTML
<h1>Contact Page</h1><p>Contact us at contact@example.com.</p><ahref="/">Go to Home</a><br><ahref="/about/">Go to About</a>

3. Define URL patterns in urls.py:

Python
fromdjango.urlsimportpathfrom.importviewsurlpatterns=[path('',views.home_view,name='home'),path('about/',views.about_view,name='about'),path('contact/',views.contact_view,name='contact'),]

Output:

1. Home Page:

HomePageDjangoApp
Home Page

2. Click “Go to About”:

AboutPageDjangoApp
About Page

3. Click “Go to Contact”:

ContactPageDjangoApp
Contact Page

Path Converters

In Django,path converters are used in URL patterns to capture specific values from the URL and pass them to the view as arguments. For example:

  • int – Matches zero or any positive integer.
  • str – Matches any non-empty string, excluding the path separator(‘/’).
  • slug – Matches any slug string, i.e. a string consisting of alphabets, digits, hyphen and under score.
  • path – Matches any non-empty string including the path separator(‘/’)
  • uuid – Matches a UUID(universal unique identifier).

Improve
Practice Tags :

Similar Reads

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 ourCookie 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

[8]ページ先頭

©2009-2025 Movatter.jp