In this section, we are going to config URL in Django. Here are some tips.
URL Configuration in Django
-
In Newsapp package create a urls.py file to redirect its own URL.
-
And then in views.py from Newsapp package,
import HttpResponse
which aims to show what we want to show on page.
from django.shortcuts import render
from django.shortcuts import HttpResponse
# Create your views here.
def News(request):
return HttpResponse('<h1>This is our latest news</h1>')
- And next, in Newsapp\urls.py create the route.
from django.urls import path
from .views import News, Home, Contact
urlpatterns = [
path('news/', News, name='news'),
]
- Next, to open it in browser, we still should change urls.py in TestPro package. Remember to add
include
in the import part.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('Newsapp.urls')),
]
- And then in TestPro, change part of settings.py file in INSTALLED_APPS segment.
# Application definition
INSTALLED_APPS = [
'Newsapp', # new added
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
- Repeat the steps above-mentioned to create “contact” and “home” page yourself.
- Here is the result.