You are reading the article How To Create A Django Url With Examples updated in September 2023 on the website Dacquyenphaidep.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested October 2023 How To Create A Django Url With Examples
Introduction to Django URLURL 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 chúng tôi 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.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
How to Create a Django URL?Let me guide you on creating a URL in Django.
1. Creating a url USING PATH()Syntax:
path(route, view, kwargs=None, name=None)urls.py:
from django.contrib import admin from chúng tôi import url,include from chúng tôi 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 chúng tôi import url,include from chúng tôi 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 indexes page can load only the specified index by using a question mark in regex.
3. Creating a Django url Through INCLUDEThe 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 chúng tôi 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 chúng tôi in place.
Django app urls.py: First, a chúng tôi file needs to be created within the application. Each project in Django should maintain its own chúng tôi file for every application. This ensures effortless inclusion and exclusion of applications from the project.
Like usual chúng tôi this file contains the import of the url class from the chúng tôi 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 chúng tôi file inside the individual Django application.
from django.contrib import admin from chúng tôi import url from Django_app1 import views urlpatterns = [ url(r'formpage/',views.formView,name='form'), ] from django.contrib import admin from chúng tôi 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 URLSThe 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 chúng tôi import url,include from chúng tôi 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 chúng tôi 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()2. Tag the Template folder in chúng tôi file: The chúng tôi 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.
4. Render the html file in chúng tôi 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 chúng tôi import HttpRespons def index(request_iter): return render(request_iter,'design.html')
Import the library from chúng tôi import url.
url(url_path, view_to_be_tagged, name_for_this_view)Example
from django.contrib import admin from chúng tôi import url from Django_app1 import views
Reload the server using the python chúng tôi runserver command and verify the webpage.
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 23, 2023 - 13:33:00 Django version 3.0.7, using settings 'educba.settings' Quit the server with CTRL-BREAK.
Reload the server using the python chúng tôi runserver command and verify the webpage.
Output:
6. Django URL Error CodesError Code Meaning
400 Bad request
403 Permission denied
404 Page not found
500 Server Error
Recommended ArticlesWe hope that this EDUCBA information on the “Django URL” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
You're reading How To Create A Django Url With Examples
Update the detailed information about How To Create A Django Url With Examples on the Dacquyenphaidep.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!