Python 之Django

时间:2021-10-07 20:34:34

1.安装Django(下载慢的时候用MaxVPN)

  pip3 install django

2.Django处理流程

  新建project(mysite),执行dj(mysite),然后在console界面中运行 D:\Python\django_project>python manage.py startapp cmdb,创建cmdb的APP。

3.Django采用MTV框架。M=Modals(数据库),T=Template(HTML模板),V=Views(用户处理逻辑)

  在配置文件urls.py中指定路由关系

from cmdb import views

urlpatterns = [
#url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
]

  在views.py中定义用户的处理逻辑

def index(request):
return (HttpResponse(''))

  这样,在执行了dj(site)之后,可以通过IE访问到我们编写的程序逻辑:http://127.0.0.1:8000/index/

4.进一步我们需要返回自己编写的HTML的时候,而不是通过HttpResponse返回。我们需要新建一个templates文件夹,在里面新建index.html文件,然后写上自定义的HTML文件:

<body>
<table border="1 solid red">
<tr>
<th>TITLE1</th>
<th>TITLE2</th>
<th>TITLE3</th>
</tr>
<tr>
<td>星期一</td>
<td>星期二</td>
<td>星期三</td>
</tr>
</table>
</body>

  然后,改写用户逻辑里面的views.py

def index(request):
# return (HttpResponse('123'))
return render(request,'index.html')

  这样再通过http://127.0.0.1:8000/index/访问的时候,就可以访问到在template文件夹下定义的index.html文件了。

  如果在执行程序的时候,报找不到template的错误,那么是settings里面定义的路径的问题

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

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',
],
},
},
]

5.导入静态文件

  在mysite下面建立文件夹static

  在views.py里面添加引用

<script src="/fff/jquery-1.12.4.js"></script>

  在settings.py里面定义静态文件的路径

STATIC_URL = '/fff/'

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

  注意这里静态文件的URL要与src引入的路径相匹配,然后通过http://127.0.0.1:8000/fff/jquery-1.12.4.js访问JQuery成功。

6.表单的提交

  在index.html里定义HTML模板

    <h1>用户输入</h1>
<form action="/index/" method="POST">
<input type="text" name="user"/>
<input type="text" name="email"/>
<input type="submit" value="提交"/>
</form>

  在views.py中获取到表单的数据

def index(request):
# return (HttpResponse('123'))
if(request.method == "POST"):
user = request.POST.get("user",None);
email = request.post.get("email",None)
print (user,email)
return render(request,'index.html')

  执行的时候报错:

Forbidden (403)
CSRF verification failed. Request aborted.
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.

  在settings.py文件中找到MIDDLEWARE,并注释其中一行:

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',
]

  提交表单数据,可以看到结果:

[28/Oct/2016 01:58:56] "GET /index/ HTTP/1.1" 200 655
aa bb
[28/Oct/2016 01:59:00] "POST /index/ HTTP/1.1" 200 655

  这样显示数据不行,必须要在网页文件中显示才行,因此,我们需要改写views.py文件

USER_INPUT=[
{'user':'u1','email':'e1'},
{'user':'u2','email':'e2'},
] def index(request):
# return (HttpResponse('123'))
if(request.method == "POST"):
user = request.POST.get("user",None)
email = request.POST.get("email",None)
temp = {'user':user,'email':email}
USER_INPUT.append(temp)
print (user,email)
return render(request,'index.html',{'data':USER_INPUT})

  同时,我们定义显示HTML的格式:

    <h1>数据展示</h1>
<table border="1">
{% for item in data %}
<tr>
<td>{{ item.user }}</td>
<td>{{ item.email }}</td>
</tr>
{% endfor %}
</table>

  并且,在HTML文件中{% %}的写法会自动循环表单中提交的数据,然后将其显示出来。Django后台帮我们把这个循环改写成了python的循环,item.user和item.email就相当于字典的key值。

  这样操作以后,执行http://127.0.0.1:8000/index/,然后通过前台就可以添加数据并且实时的显示了。

7.上面表单的提交在页面刷新以后就没有了,因为内容是存放在缓存中的,现在,我们需要将数据存放在数据库当中,改写之前的代码。

  在models.py中创建UserInfo的类:

class UserInfo(models.Model):
user = models.CharField(max_length=32)
email = models.CharField(max_length=32)

  在settings.py中注册cmdb,并且查看DATABASES的设置:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cmdb',
]

  执行命令创建数据库,表

D:\Python\mysite>python manage.py makemigrations
Migrations for 'cmdb':
cmdb\migrations\0001_initial.py:
- Create model UserInfo D:\Python\mysite>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, cmdb, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying cmdb.0001_initial... OK
Applying sessions.0001_initial... OK

  在用户逻辑views.py中需要引入models操作数据库

from cmdb import models

def index(request):

    if(request.method == "POST"):
u = request.POST.get("user",None)
e = request.POST.get("email",None)
models.UserInfo.objects.create(user=u,email=e)
data_list = models.UserInfo.objects.all()
# for item in data_list:
# print (item.user,item.email)
return render(request, 'index.html',{'data':data_list})

  在显示页面上index.html显示数据库中提取的数据:

<body>
<table border="1 solid red">
<tr>
<th>TITLE1</th>
<th>TITLE2</th>
<th>TITLE3</th>
</tr>
<tr>
<td>星期一</td>
<td>星期二</td>
<td>星期三</td>
</tr>
</table>
<script src="/fff/jquery-1.12.4.js"></script> <h1>用户输入</h1>
<form action="/index/" method="POST">
<input type="text" name="user"/>
<input type="text" name="email"/>
<input type="submit" value="提交"/>
</form> <h1>数据展示</h1>
<table border="1">
<tr>
<th>用户名</th>
<th>邮箱</th>
</tr>
{% for item in data %}
<tr>
<td>{{ item.user }}</td>
<td>{{ item.email }}</td>
</tr>
{% endfor %}
</table> </body>
MIDDLEWARE