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. The same applies to Django also, So from a Django perspective setting the necessary URL’s are handled in the urls.py section of the framework and there are several techniques through which the URL’s are maintained through the application. This information on how classifiable Django handles its URL’s and what are the techniques involved for keeping these URL’s assembled are described below.
How to Create a Django URL?
How to create a Django url is given below:
1. Creating a url USING PATH()
The path method allows returning of an element to be included in URL patterns tuple which will be used as an url pattern. This was introduced in Django version 2.0 along with the re_path() method.
Syntax:
path(route, view, kwargs=None, name=None)
Example
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 the use of 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)
Example
urls.py:
rom 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 :
Note: The question mark in regex allows the indexes page to get loaded with only the index mentioned in it.
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 inclusion of these URL’s in the main project urls.py file will help to easily access the web pages associated with that Django application. 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. So this means every Django application which was expected to be developed as a part of the Django project is considered to hold an individual urls.py file within it. This individual urls.py file will bring flexibility for the applications so that they can be easily plugged and plugged out from the main project.
As like usual urls.py, this file contains the import of the url class from the django.conf.URLs library, most importantly the views file for this application is expected to be imported here from the Django application mentioned. The view method which has been imported needs to be specified in the import of the views from the Django application. additionally as like mention in the URL declarations above here again a name s associated to the url mapping and the path of the mapping is also placed. So this section acts as the formulation of 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 be acting as the premiere URLs linking the library for the entire application. here all the URLs from the Django application can be included which means every page addressed in those applications can be accessed here sophisticatedly. The first major element to be taken care 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 to 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.
Example
The below example shows how the url value can be converted to a string format and passed 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/<username:uname>/',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: First to hold the html design for the web page the necessary templates are expected to be created. these templates are stored in the template folder, So for a Django project all the code associated. The template folder has to be created under the primary project folder.
2. Tag the Template folder in settings.py file: The settings.py file needs to have the tag for the templates folder so that all templates are accessible for the entire Django project. This brings in the capability of accessing all the html files which are been placed as a part of the templates folder.
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)
from django.contrib import admin
from django.conf.urls import url
from Django_app1 import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'admin/', admin.site.urls), ]
- Reload the server using python manage.py runserver command and verify the webpage.
- The console will be pasted with the below listed server messages, So the time of the server to be kickstarted can be identified from this, also the http link and the version of the Django server which is been used will also 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 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 |