WEB开发

168 阅读1分钟

djang url控制

创建项目

django-admin startproject mysite

创建app,创建成功项目以后,cd进入mysite

python manage.py startapp app01

数据库迁移命令

python manage.py makemigrations

执行数据库迁移文件

python manage.py migrate

运行项目

python manage.py runserver

指定端口运行项目

python manage.py runserver 8080

指定端口IP运行项目

python manage.py runserver 0.0.0.0:8080

创建超级用户

python manage.py createsuperuser

修改用户密码

python manage.py changepassword username

进入shell模式

python manage.py shell

反向生成models

python manage.py inspectdb > app01/models.py

静态文件

在stettings里添加 STATICFILES_DIR=[ os.path.join('BASE_DIR','static') ] 同事在工程目录下建个文件夹static

  1. 可以放jquery
  2. 可以放css
  3. 可以js

路由分发

re_path(r'^articles/2003/$',views.special_case_2003),
re_path(r'^articles/([0-9]{4})$',views.year_archive),
#有名传参分组
re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})$',views.month_archive),

当前应用的app01目录下建个url做路由分发,在主工程名下的url内导入

from django.urls import path,re_path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('timer/', views.timer),
    # 路由配置:
    # re_path(r'^articles/2003/$',views.special_case_2003),
    # re_path(r'^articles/([0-9]{4})$',views.year_archive),
    # re_path(r'^articles/([0-9]{4})/([0-9]{2})$',views.month_archive),
    # re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})$',views.month_archive),#有名传参分组
    # 分发
    re_path(r'app01/',include('app01.urls')),
]

反向解析

url re_path(r'^articles/2003/$',views.special_case_2003,name = s_c_2003),

html {%url 's_c_2003'%}

from django.urls improt reverse

url = reverse('s_c_2003',args=(4009,))

名称空间

re_path(r'app01/',include(('app01.urls','app01')))

在反向解释:reverse("app01:index")

url控制器的path方法

 1.str 匹配除了路径分割符(/)之外的非空字符串
 2.int 匹配正整数,包括0
 3.slug 匹配字母,数字横杠,下划线组成的字符串
 4.uuid 匹配格式化的uuid ,如:075194-fs5
 5.path 匹配任何非空字符串,包含了路径分割符除了(?)

 
 path("articles/"<path:year>",views.path_year)
 在views视图函数了重写path_year
 

path的自定义转换器

1. 建一个py文件urlconvert
2. 建个类
 class MonConvert:
     regex = '[0-9]{2}'
     def to_python(self,value):
         return int(value)
         
     def to_url(self,value):#反向解析
         return '%04d' %value
     
 3.在url里注册
 from app01.urlconvert import MonConvert
 #注册自定义转换器
 reguster_converter(MonConvertm,"mc")