Python 23 Django

Zero, Basic Configuration Operation

1. Create a program Django

Command: django-admin startproject name

2, program directory

3, the configuration file

(1), the database

1
2
3
4
5
6
7
8
9
10
DATABASES  =  {
     'default' : {
     'ENGINE' 'django.db.backends.mysql' ,
     'NAME' : 'dbname' ,
     'USER' 'root' ,
     'PASSWORD' 'xxx' ,
     'HOST' : '',
     'PORT' : '',
     }
}
1
2
3
4
5
6
# 由于Django内部连接MySQL时使用的是MySQLdb模块,而python3中还无此模块,所以需要使用pymysql来代替
  
# 如下设置放置的与project同名的配置的 __init__.py文件中
  
import  pymysql
pymysql.install_as_MySQLdb() 

(2), template

1
2
3
TEMPLATE_DIRS  =  (
         os.path.join(BASE_DIR, 'templates' ),
     )

(3), static files

1
2
3
STATICFILES_DIRS  =  (
         os.path.join(BASE_DIR, 'static' ),
     )

 

A, url routing system

1, url with variables

path('<year>/<int:month>/<slug:day>',``````)

    Using the URL <> variables may be provided, with a colon in parentheses divided into two parts, before the colon is the variable type, the string, without the type, the variable name after the colon.

2, based on regular routes

url(r'^index/(\d*)', views.index),
url(r'^manage/(?P<name>\w*)/(?P<id>\d*)', views.manage),

3, set the name for the route map

url(r'^home', views.home, name='h1'),
url(r'^index/(\d*)', views.index, name='h2'),

设置名称后,可以在视图和模板中调用:

  • 视图中:reverse(“h2”, args=(2012,))   路径django.urls.reverse
  • 模板中:{% url 'h2' 2012%}

4、路由分发

    在APP中创建urls.py文件,将属于该APP的url地址都写入到这个文件中,当程序收到用户发送的请求时,先在根目录的urls.py文件中查找该地址属于哪个APP,将这个请求分发到该APP中,然后在APP的url.py中找到具体信息。

from django.urls import path,include #include就是分发函数
     urlpatterns = [
         path('1/',include(‘index.urls’))     #index是APP名字  
    ]

    给URL起别名看似没有必要,但是如果改变了URL的路径,则需要修改所有html中用到该URL的地方,这个时候使用别名就可以省去这些麻烦。

5、Django的路径添加问题

  在settings中添加 APPEND_SPASH = False 可以阻止django自动添加url最后的斜杠。

Guess you like

Origin www.cnblogs.com/yinwenjie/p/10935240.html
Recommended