一.创建第一个django的app
1.1 在终端根目录下执行命令
## 创建一个app
python manage.py startapp <app名称>
例:python manage.py startapp book
1.2创建成功后生成文件如下
二.url两种获取参数的方式
book/views.py
from django.shortcuts import render, HttpResponse
# Create your views here.
"""
从url中获取参数
1.查询字符串(query_string):http://localhost:8000/book?name=xxx&age=xxx&className=xxx
2.从path获取:http://localhost:8000/book/xxxx
"""
# 1.查询字符串(query_string):http://localhost:8000/book?name=lsy&age=23&className=幼儿园中班
def book_query_string(request):
"""
:param request: name,age,class_name
:return: 个人介绍
"""
name = request.GET.get('name')
age = request.GET.get('age')
class_name = request.GET.get('className')
return HttpResponse(f"我的名字是{name},今年{age}岁了,我是{class_name}的")
# 2.从path获取:http://localhost:8000/book/10
def book_detail(request, book_id):
"""
:param book_id:
:param request: id:book_id
:return:当前book的id
"""
return HttpResponse(f"这本书的id是{book_id}")
djangoProject/urls.py
"""
URL configuration for djangoProject project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.shortcuts import HttpResponse
from book.views import book_query_string, book_detail
"""
django里的第一个函数必须是request,不写会报错
"""
def index(request):
return HttpResponse("Hello, world. You're at the index of djangoProject.")
urlpatterns = [
path('admin/', admin.site.urls),
path('', index), # 不写path的第一个参数 那么就是/
path('test', index), # 默认情况下是自带/路径的 在这里定义test访问/test 可以访问
path('book', book_query_string), # 往里传参数 如果参数没有 view里还使用了 那么会返回None book_detail
path('book/<int:book_id>', book_detail), # <boo_id> 表示/book/id的值 <int:book_id> 的int 表示他只接收int类型的参数,否贼会报404
]
2.1 通过查询字符串(query_string):http://localhost:8000/book?name=lsy&age=23&className=幼儿园中班
2.2 通过从path获取:http://localhost:8000/book/10
2.2.1 path里的类型限制
注意:
path里面定义的int 所以他后面必须跟的是整数类型,如果填写其他类型 那么将会报错404