Django, urls的参数name的demo
Django的路由变化
遇到需要修改路由的需求,特别记录一下
项目开始
django-admin startproject sandboxOA. # 外部文件夹可以改变名字, '.'的意思是上一级不需要再添加一个sandboxOA文件
创建应用
python manager.py startapp blog
blog的配置
在应用中增加一个urls.py的路由配置, name 的配置主要是这里的这三个,nba, lakers, rockets
from django.urls import path
from . import views
urlpatterns = [ #也要放到urlpatterns 变量中
path('',views.book, name='book'), #/book
path('detail/<int:book_id>/',views.book_detail, name='book2'), #主urls.py会跟这个进行拼接 注意不要多加/
path('list/',views.book_list), # 'list/'前面没有/
path('nba', views.NBA_views),
path('lakers/win', views.lakers_views, name="lakers"), # 给路由取一个别名
path(r'rockets/<int:num>/', views.rockets_views, name="rockets")
]
在blog/views.py中编写代码
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def hello(request):
return HttpResponse('欢迎使用Django!')
def book(request):
return HttpResponse('欢迎使用Django!')
def book_detail(request, book_id):
text = '图书的id是:%s' % book_id
return HttpResponse(text)
def book_list(request):
return HttpResponse("图书列表页")
def index(request):
return render(request, 'book.html')
def NBA_views(request):
return render(request, "NBA.html")
def lakers_views(request):
return render(request, "lakers.html")
def rockets_views(request, num):
print(num)
# return HttpResponse("火箭列表页")
return render(request, "rockets.html")
在根项目中编写代码
setting.py 配置 缺少一个db得配置
"""
Django settings for sandboxOA project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent # 这个是当前目录
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-rzx-%k2dkfb8^il2z6^)u72#6ov$1v@rt+k-fu6x^%qg8aq#sj'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# DEBUG = False
ALLOWED_HOSTS = ['*'] # 修改后,表示任何域名都能访问。如果指定域名的话,在''里放入指定的域名即可
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog' # 注册一个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 = 'sandboxOA.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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 = 'sandboxOA.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
# }
# Password validation
# https://docs.djangoproject.com/en/3.2/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.2/topics/i18n/
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.2/howto/static-files/
STATIC_URL = '/static/'
# 配置出一个静态文件路径
STATICFILES_DIRS = [
os.path.join(BASE_DIR,"static"),
]
#设置文件上传路径,图片上传、文件上传都会存放在此目录里
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
根项目下的 urls.py
from django.contrib import admin
from django.urls import path, include
# 对于处理静态文件如图片,CSS和文本非常重要
from django.conf import settings
from django.conf.urls.static import static
from . import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls'))
]
handler404 = views.page_not_found # 增加404
templates文件夹的下的html
NBA.html
<!-- NBA.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>体育新闻</title>
</head>
<body>
<h2>
<a href="{% url 'lakers' %}">去湖人队看看</a>
</h2>
<h2>
<a href="{% url 'rockets' 34 %}">去火箭队看看</a>
</h2>
</body>
</html>
lakers.html
<!-- lakers.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>湖人队</title>
</head>
<body>
<h1>The Los Angeles lakers</h1>
</body>
</html>
rockets.html
<!-- lakers.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>火箭队</title>
</head>
<body>
<h1>Houston Rockets!!!!!!!!!!!</h1>
</body>
</html>
这时候 运行django, 就可以看到,name的变化,可以在blog/urls.py 随意的改变 的前置了
改变一下urls
完。