Django URLS
URLs in Django are in the format of regular expressions, which are easily readable by human’s. A Regular Expression also called regex is a format for search pattern which is much cleaner and easy to read for the humans and is very logical. We will learn how to import the view functions and connecting different url-conf files with the main urls.py file. First, we will have to import the view function that we want our server to run when the URL is matched. For that, we have to import the function from the views.py file.
urls.py:
from django.contrib import admin
from django.urls import path
#from helloworld.views import Index
from helloworld.views import Hello
urlpatterns = [
path('admin/', admin.site.urls),
path('helloworld/',Hello)
]
view.py:
#from django.shortcuts import render
from django.http import HttpResponse
def Hello(request):
return HttpResponse("Hello")
Different formats of url:
There are many way to write django path here we include some important for Django any projects:
-
By using path and its method:
path('helloworld/',Hello)
-
Using path with name:
from django.urls import path
from . import views
urlpatterns = [
path('', views.Hello, name='Hello'),
]
-
Using url regular expression:
url(r'^$', views.Hello, name='Hello' )