Django(4) URL Configuration in Django

In this section, we are going to config URL in Django. Here are some tips.

URL Configuration in Django

  1. In Newsapp package create a urls.py file to redirect its own URL. Django(4)_URL_Configuration_in_Django_1.png

  2. 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>')

  1. 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'),
]

  1. 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')),
]

  1. 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',
]
  1. Repeat the steps above-mentioned to create “contact” and “home” page yourself.
  2. Here is the result.
    Django(4)_URL_Configuration_in_Django_2.png
    Django(4)_URL_Configuration_in_Django_3.png
    Django(4)_URL_Configuration_in_Django_4.png

So far, you have learnt how to add URLs to a project and run it on a server. Hopefully, it helps.

猜你喜欢

转载自blog.csdn.net/Moses_SU/article/details/127662611
今日推荐