Django可以自己设置URL,没有框架限制,纯python代码,是一个简单的python模式(简单的正则表达式)。
1. 可以再myweb项目中的urls直接写。
from django.contrib import admin
from django.urls import path, re_path
from myapp import views
urlpatterns = [
# path('admin/', admin.site.urls),
path("aa/", views.index, name ="index"), # 这里写name,是为了在views.py中用reverse查到
path("add/", views.add, name = "add"),
path("find/<int:sid>", views.find),
path("find/<int:sid>/<str:name>", views.find2, name="find2"), # http://localhost:8000/find/20/lisi
path("edit/", views.update),
re_path(r"^fun/([0-9]{4})/([0-9]{2})$",views.fun), # http://localhost:8000/fun/2021/08
re_path(r"^fun/(?P<yy>[0-9]{4})/(?P<mm>[0-9]{2})$",views.fun2) # 通过?p<name>可以在views中获取到name。具体详见views.py
]
2. views.py视图。
from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.urls import reverse
from django.shortcuts import redirect
# Create your views here.
def index(request):
print(reverse("add")) # reverse通过路由名称反向生成url请求地址
print(reverse("index"))
print(reverse("find2", args=(100,'lisi')))
return redirect(reverse("find2", args=(100,'lisi'))) # 重定向
# return HttpResponse("Hello world")
def add(request):
return HttpResponse("add....")
def find(request,sid):
return HttpResponse("find...%d"%(sid))
def find2(request,sid=0,name=""): # 可以设置默认值,输url的时候,可以不输sid和name,http://localhost:8000/find/
return HttpResponse("find...%d:%s"%(sid,name))
def update(request):
# return HttpResponse("update...")
raise Http404('update not exit!')
def fun(request, y, m):
return HttpResponse("information: %s年%s月"%(y,m))
def fun2(request, mm, yy):
return HttpResponse("information: %s年%s月"%(mm,yy))
3. 新建一个404.html
在根目录下,新建一个文件夹templates,放入404.html。再配置setting,三个部分,如4中所示。
<!DOCTYPE html>
<html>
<head>
<title>404</title>
</head>
<body>
<center>
<h2>404 not found</h2>
<h3>{{exception}}</h3>
</center>
</body>
</html>
4. setting 下的配置
"""
Django settings for myweb project.
Generated by 'django-admin startproject' using Django 3.0.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_iezz#vz_n-r^*dlny_-10n#*0cbcna#@9k50+_3)(((e0k(hz'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False # 配置404
ALLOWED_HOSTS = ['*'] # 配置404
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig', # 新建的子项目app放进去
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myweb.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")], # 配置404
'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',
],
},
},
]
WSGI_APPLICATION = 'myweb.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
DATABASES = { # 配置数据库连接
'default':{
'ENGINE':'django.db.backends.mysql',
'NAME' : 'Student',
'USER': 'root',
'PASSWORD':'hang123',
'HOST':'localhost',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
# LANGUAGE_CODE = 'en-us'
# TIME_ZONE = 'UTC'
# 设置后套管理是中文界面
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'