How to Create URL in Django: Simple Guide with Examples
In Django, you create URLs by defining patterns in a
urls.py file using the path() or re_path() functions. These patterns map URL strings to views, letting Django know what code to run when a user visits a specific URL.Syntax
In Django, URLs are created inside a urls.py file using the path() function. The basic syntax is:
route: a string pattern for the URL path.view: the function or class that handles the request.name: an optional name to refer to the URL elsewhere.
Example: path('home/', views.home_view, name='home')
python
from django.urls import path from . import views urlpatterns = [ path('home/', views.home_view, name='home'), ]
Example
This example shows a simple Django app URL configuration that maps the URL /hello/ to a view that returns a greeting message.
python
from django.http import HttpResponse from django.urls import path # Define the view function def hello_view(request): return HttpResponse('Hello, Django!') # URL patterns list urlpatterns = [ path('hello/', hello_view, name='hello'), ]
Output
When you visit http://localhost:8000/hello/ in your browser, you will see the text: Hello, Django!
Common Pitfalls
Common mistakes when creating URLs in Django include:
- Forgetting to import the view function or module.
- Not including a trailing slash in the URL pattern, which can cause 404 errors if
APPEND_SLASHis not enabled. - Using the wrong function like
url()instead ofpath()in modern Django versions. - Not adding the
urls.pyto the project’s mainurls.pyviainclude().
Example of wrong and right usage:
python
from django.urls import path from . import views # Wrong: missing trailing slash and old function # urlpatterns = [ # url('hello', views.hello_view), # url() is legacy # ] # Right: urlpatterns = [ path('hello/', views.hello_view, name='hello'), ]
Quick Reference
Summary tips for creating URLs in Django:
- Use
path()for simple URL patterns. - Use
re_path()if you need regular expressions. - Always add a trailing slash
/to your URL patterns. - Name your URLs with
name=for easy reverse lookup. - Import views correctly and include app URLs in the project’s main
urls.py.
Key Takeaways
Create URLs in Django using the path() function inside urls.py files.
Map URL patterns to view functions or classes to handle requests.
Always include trailing slashes in URL patterns to avoid 404 errors.
Name your URLs for easy reference in templates and redirects.
Import views and include app URLs properly in the main project urls.py.