Updated May 4, 2023
Introduction to Django URL
URL is a path through which a specific web-based application and one particular page in that web application can be reached. So for any web-oriented application setting these url paths is a very key necessity. Django manages the necessary URLs in the urls.py section of the framework, following various techniques to maintain them throughout the application. The methods used to keep the URLs organized in Django are discussed below.
How to Create a Django URL?
Let me guide you on creating a URL in Django.
1. Creating a url USING PATH()
Django introduced the path method and re_path() method in version 2.0, allowing for the inclusion of an element as a URL pattern within a tuple that can be used for URL patterns.
Syntax:
path(route, view, kwargs=None, name=None)
urls.py:
from django.contrib import admin
from django.conf.urls import url,include
from django.urls import path
from Django_app1 import views
admin.autodiscover()
urlpatterns = [
path('index/',views.template_view,name='template'),
url(r'^myapp/', include('Django_app1.urls')),
url(r'admin/', admin.site.urls),
]
Output:
2. Creating a Django URL USING RE_PATH()
The re_path() method allows using Python regular expressions in URLs. This was introduced in version 2.0, along with the path() method.
Syntax:
path(route, view, kwargs=None, name=None)
urls.py:
from django.contrib import admin
from django.conf.urls import url,include
from django.urls import path , re_path
from Django_app1 import views
admin.autodiscover()
urlpatterns = [
re_path('^indexs??/$',views.template_view,name='template'),
url(r'^myapp/', include('Django_app1.urls')),
url(r'admin/', admin.site.urls),
]
Output :
3. Creating a Django url Through INCLUDE
The technique involves creating url patterns within each app. This will bring more flexibility when the app needs to be plugged into a different application. Just making the inclusion of these URL’s in the main project urls.py file will help to access the web pages associated with that Django application easily. Below are the steps related to making an include-oriented Django urls.py in place.
Django app urls.py: First, a urls.py file needs to be created within the application. Each project in Django should maintain its own urls.py file for every application. This ensures effortless inclusion and exclusion of applications from the project.
Like usual urls.py, this file contains the import of the url class from the django.conf.URLs library, and most importantly, the views file for this application is expected to be imported here from the Django application mentioned. When importing views from a Django application, you need to specify the method of the view being imported. As mentioned earlier in the URL declarations, the URL mapping is associated with a name and also includes the mapping path. So this section acts as the formulation of the urls.py file inside the individual Django application.
from django.contrib import admin
from django.conf.urls import url
from Django_app1 import views
urlpatterns = [
url(r'formpage/',views.formView,name='form'),
]
Main project urls.py: This urls.py file will act as the premiere URL linking the library for the entire application. Here, all the URLs from the Django application can be included, meaning every page addressed in those applications can be accessed here sophisticatedly. The first significant element to be taken care of is that the include method is imported from django.conf.urls library. This is the first key thing to be taken care of. Next, ensure the admin class is also imported. This admin class is useful in setting the auto-discover method. At last, it needs to be ensured that the urls.py file from the Django application is included as an item in the urlpatterns tuple. Making this include will automatically import all the urls from that corresponding application.
from django.contrib import admin
from django.conf.urls import url,include
from Django_app1 import views
admin.autodiscover()
urlpatterns = [
url(r'^$',views.template_view,name='template'),
url(r'^myapp/', include('Django_app1.urls')),
url(r'admin/', admin.site.urls),
]
Output:
4. Setting Converters in URLS
The converters are responsible for converting a dynamic value in the URL to a needed value format.
In the example below, you can see how to convert the URL value to a string format and then pass it into its corresponding view.
urls.py:
from django.contrib import admin
from django.conf.urls import url,include
from django.urls import path , re_path,register_converter
from django.urls.converters import StringConverter
from Django_app1 import views
admin.autodiscover()
register_converter(StringConverter, 'username')
urlpatterns = [
path('index//',views.template_view,name='template'),
# url(r'formpage/',views.formView,name='form'),
url(r'^myapp/', include('Django_app1.urls')),
url(r'admin/', admin.site.urls),
]
Views.py:
from django.shortcuts import render
from django.http import HttpResponse
from Django_app1.forms import Valueform
from django.core.exceptions import ViewDoesNotExist
from django.contrib.auth.models import User
def template_view(request_iter,uname):
template_Var = {
"Entity_name" : "Educba",
"Entity_type" : "tutorial",
"Entity_students_count" : 345,
"Error_Message" : "No Valid Entity found"
}
print("Username:",uname)
return render(request_iter,'design.html',context=template_Var)
Output:
5. Creating a Django URL Through URL()
1. Create a Template folder: To create templates for your web page’s html design, save them in the template folder located in the primary folder of your Django project.
2. Tag the Template folder in settings.py file: The settings.py file needs the tag for the templates folder to make all templates accessible for the entire Django project. This brings in the capability of accessing all the html files placed as a part of the templates folder.
import os
# Build paths inside the project like this: os.path.join(BASE_DIR,...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Template_DIR = os.path.join(BASE_DIR,'Templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Template_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]Template_DIR = os.path.join(BASE_DIR,'Templates')
3. Place an HTML file inside the Templates folder: The HTML content for the web page is drafted.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
</head>
<body>
<h1> Hello world from HTML page <h1>
</body>
</html>
4. Render the html file in views.py using render() method: For passing the newly created HTML content to the web page or, in other words, to connect the content to the webpage, the render() method is used. The render method combines a template with the context dictionary to return a HttpResponse object.
from django.shortcuts import render
from django.http import HttpRespons
def index(request_iter):
return render(request_iter,'design.html')
- Import the library from django.conf.urls import url.
- Declare a url entry in the urlpatterns list.
url(url_path, view_to_be_tagged, name_for_this_view)
Example
from django.contrib import admin
from django.conf.urls import url
from Django_app1 import views
- Reload the server using the python manage.py runserver command and verify the webpage.
- The console will display the server messages listed below, enabling you to ascertain the precise time for initiating the server. Also, the http link and the version of the used Django server will be displayed.
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
June 23, 2020 - 13:33:00
Django version 3.0.7, using settings 'educba.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
- Reload the server using the python manage.py runserver command and verify the webpage.
Output:
6. Django URL Error Codes
Error Code | Meaning |
400 | Bad request |
403 | Permission denied |
404 | Page not found |
500 | Server Error |
Recommended Articles
We hope that this EDUCBA information on the “Django URL” was beneficial to you. You can view EDUCBA’s recommended articles for more information.