Django最强大的部分之一是自动管理界面。它从模型中读取元数据,以提供一个快速的,以模型为中心的界面,受信任的用户可以在其中管理您网站上的内容。管理员的建议用法仅限于组织的内部管理工具。它并非旨在构建您的整个前端。
初始化Django
pip install django # 安装
django-admin startproject MyProject # 创建项目
D:MyProject> django-admin startapp MyWeb # 创建APP
D:MyProject> python manage.py runserver 0.0.0.0:80 # 启动Django
D:MyProject> python manage.py shell # 进入Django交互shell
D:MyProject> python manage.py dbshell # 进入DBShell
D:MyProject> python manage.py check # 检查Django完整性
修改一下django的配置文件settings.py
,导入我们生成APP的名字.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware', # 注释掉此行
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MyWeb.apps.MywebConfig' # 添加此行,导入我们的APP的名字
]
然会修改urls.py
在这里写一条路由记录.
from MyWeb import views
urlpatterns = [
path('admin/', admin.site.urls),
path("hello/",views.hello,name="hello")
]
最后我们在views.py
视图函数里添加一条路由.
from django.shortcuts import HttpResponse
def hello(request):
return HttpResponse("<h1>hello lyshark</h1>")
有时候我们需要在本地引入JS或者静态资源,此时你需要修改一下Django的setting.py
里面的路径.
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
# 此时我们的默认路径是/static/,那么前端就可以直接调用<script src="/static/lyshark.js">
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'static')
)
邮件发送
# name:settings.py
STATIC_URL = '/static/'
EMAIL_USER_TLS = True
EMAIL_PORT = 25
EMAIL_HOST = "smtp.163.com"
EMAIL_HOST_USER = "smtpwho@163.com"
EMAIL_HOST_PASSWORD = "授权密码"
# name: views.py
from django.shortcuts import render,HttpResponse
from django.core.mail import send_mail, send_mass_mail, EmailMultiAlternatives
def send(request):
if request.method == "GET":
return HttpResponse("""
<form action="/send/" method="POST">
<input type="submit" value="发送邮件">
</form>
""")
else:
ret = send_mail("Django 邮件通知", # 邮件名称
"这是一封来自Django的邮件", # 邮件内容
"smtpwho@163.com", # 发信邮箱
['admin@blib.cn']) # 收信邮箱
if ret:
return HttpResponse("完成")
else:
return HttpResponse("失败")
使用类视图映射
# name:urls.py
from MyWeb import views
urlpatterns = [
path('index/',views.index.as_view())
]
# name:views.py
from django import views
class index(views.View):
def get(self,request,*args,**kwargs):
pass
def post(self,request,*args,**kwargs):
pass
简单的路由编写
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index,name="index"), # 一条访问主站的路由
path('login/id=<int:id>&name=<str:name>',views.login,name="login"), # 名称后面传递参数
path('add/<int:x>/<int:y>/',views.add,name="add") # 路径中传递参数
]
from django.shortcuts import render,HttpResponse
def index(request):
return render(request,"index.html")
def login(request, id, name):
return HttpResponse("用户ID{} , 用户名{} ".format(id,name))
def add(request,x,y):
temp = int(x)+int(y)
return HttpResponse("相加结果:{}".format(temp))
使用模板传递简单的参数
<b>用户名: {{ user }} 密码:{{ pasd }} 标题:{{ title }}</b>
def index(request):
username = "lyshark"
password = "123123"
title = "hello lyshark"
return render(request,"index.html",{"user":username,"pasd":password,"title":title})
后端组装数据然后传递给前端
<b>用户名: {{ user }} 密码:{{ pasd }} 标题:{{ title }}</b>
def index(request):
username = "admin"
password = "123123"
title = "hello lyshark"
dict = {
"user": username,
"pasd": password,
"title": title
}
return render(request,"index.html",dict)
通过info变量遍历出指定字段元素
<b>站点名称:{{ info.site }} 站点描述:{{ info.content }}</b>
def index(request):
info = {"site":"blib.cn","content":"hello lyshark"}
return render(request,"index.html",{"info":info})
通过for语句遍历打印列表数据
{% for item in total %}
<b>打印数据: {{ item }}</b><br>
{% endfor %}
def index(request):
lists = ["HTML","CSS","JAVASCRIPT","Python","JQuery"]
return render(request,"index.html",{"total":lists})
通过for语句倒序循环打印
{% for item in total reversed%}
<b>打印数据: {{ item }}</b><br>
{% endfor %}
def index(request):
lists = ["1","2","3","4","5"]
return render(request,"index.html",{"total":lists})
通过使用for循环遍历字典
{% for key,value in info.items %}
{{ key }} : {{ value }}
{% endfor %}
def index(request):
info = {"site":"blib.cn","content":"hello lyshark"}
info1 = {"site": "blib.cn", "content": "hello admin"}
return render(request,"index.html",{"info":info,"info1":info1})
Django 实现选择框选择
<form action="/index/" method="post">
选择A:
<select name="tag_select_a">
{% for item in total_a %}
<option value = "{{ item }}"> {{ item }} </option>
{% endfor %}
</select>
选择B:
<select name="tag_select_b">
{% for item in total_b %}
<option value = "{{ item }}"> {{ item }} </option>
{% endfor %}
</select>
<input type="submit" value="提交选择">
</form>
def index(request):
if request.method == "GET":
tag_select_a = ["HTML", "CSS", "JAVASCRIPT", "Python", "JQuery"]
tag_select_b = ["MySQL","Oracle","MSSQL"]
return render(request, "index.html", {"total_a": tag_select_a,"total_b": tag_select_b})
elif request.method == "POST":
select_a = request.POST.get("tag_select_a")
select_b = request.POST.get("tag_select_b")
return HttpResponse("选择A: {} 选择B: {}".format(select_a,select_b))
简单的路径拼接
<a href="{{ request.path }}?uid=1">当前网址加参数</a>
<!--获取当前路径 拼接成 /add/4/5-->
{{ request.path }}{% url 'add' 4 5 %}
def add(request,x,y):
temp = int(x)+int(y)
return HttpResponse("相加结果:{}".format(temp))
def index(request):
return render(request,"index.html")
判断用户是否登录
{% if request.user.is_authenticated %}
{{ request.user.username }},您好!
{% else %}
请登陆,这里放登陆链接
{% endif %}
使用if语句判断数据
{% if username == "lyshark" and password == "123123" %}
<b>恭喜你</b>
{% elif username == "admin" or password == "123123" %}
<b>欢迎管理员</b>
{% else %}
<b>这个都不是</b>
{% endif %}
def index(request):
username = "admin"
password = "123123"
return render(request,"index.html",{"username":username,"password":password})
if语句也可以判断列表元素
{% if 1 in list %}
<b>在里面</b>
{% elif 10 not in list %}
<b> 不在里面</b>
{% endif %}
def index(request):
list = [1,2,3,4,5]
return render(request,"index.html",{"list":list})
最后的大总结:if与for语句的结合
{% for item in info %}
{% if forloop.first %}
<b>开始了</b>
{% endif %}
{{ forloop.counter }} : {{ item }}<br>
{% if forloop.last %}
<b>最后了</b>
{% endif %}
{% endfor %}
def index(request):
list = map(str,range(100))
return render(request,"index.html",{"info":list})
forloop.counter 索引从 1 开始算
forloop.counter0 索引从 0 开始算
forloop.revcounter 索引从最大长度到 1
forloop.revcounter0 索引从最大长度到 0
forloop.first 当遍历的元素为第一项时为真
forloop.last 当遍历的元素为最后一项时为真
forloop.parentloop
用在嵌套的 for 循环中,获取上一层 for 循环的 forloop
常用的过滤器: 常用的过滤器,有以下几种.
<b> 列表长度: {{ total | length }}</b><br>
<b> 输出大小: {{ size | filesizeformat }}</b><br>
<b> 输出时间: {{ date | date:"Y-m-d" }}</b><br>
<b> 首字母大写: {{ title | capfirst }}</b><br>
<b> 从字符串中移除hello字符: {{title | cut:"hello" }}</b><br>
<b> 显示字符串第一个元素: {{ total | first }}</b><br>
<b> 显示字符串最后一个元素: {{ total | last }}</b><br>
<b> 大小写转换(upper/lower): {{ title | upper }}</b><br>
<b> 对数据切片: {{ title | slice:"2:-1" }}</b><br>
<b>截断字符:{{ title | truncatechars:5 }}</b><br>
<b>截断单词:{{ title | truncatewords:1 }}</b>
def index(request):
filesize = 10240
title = "hello lyshark"
date = datetime.datetime.now()
lists = ["1","2","3","4","5"]
return render(request,"index.html",{"total":lists,"size":filesize,"date":date,"title":title})
自定义过滤器与标签
1.首先在Django项目下的APP里面,创建一个templatetags
的目录,这个目录名不能变.
MyWeb/
__init__.py
models.py
templatetags/
__init__.py
mysimple.py
views.py
2.在templatetags
目录下创建任意的py文件,此处我们就创建一个mysimple.py
,并写入以下两条内容.
from django import template
from django.utils.safestring import mark_safe
register = template.Library() # 此处必须这样写
# simple_tag(自定义标签):不会限制传参,但不支持if
@register.simple_tag
def simple_time(var1,var2,var3):
temp = int(var1)+int(var2)+int(var3)
return temp
# filter(自定义过滤器):限制传参2个,但支持if
@register.filter
def My_filter(value, arg):
# 传递一个参数的过滤器
return str.upper(value) + arg
3.在我们需要使用自定义过滤器的时候,必须在index.html
中引入这个变量,然后在前端就可以调用了.
# name: views.py
def index(request):
title = "hello"
return render(request,"index.html",{"title":title})
# name: index.html
<!--引入自定义的过滤器-->
{% load mysimple %}
<b>自定义标签返回数值: {% simple_time 10 20 30 %}</b> <!-- 传递多个参数 -->
<b>传递一个参数的过滤器: {{ title | My_filter:'lyshark' }}</b> <!-- 传递一个参数 -->
模板与模板继承
母板: {% block title %}{% endblock %}
子板继承: {% extends "base.html" %}
子板中使用其他模板: {% include "xx.html" %}
设置标题: {% block title %}{% endblock %}
使用CSS资源: {% block css %} {% endblock %}
使用JS资源: {% block js %} {% endblock %}
1.首先创建一个base.html
文件,以作为我们的母版.
<html>
<head>
<meta charset="UTF-8">
{% block css %}{% endblock %}
</head>
<body>
<div class="pg-body">
<div class="body-menu">
<ul>
<li><a href="/user">用户管理</a></li>
<li><a href="/hosts">资产管理</a></li>
</ul>
</div>
<div class="body-content">
{% block body %}{% endblock %} <!--占位符,用于填充子版块-->
</div>
</div>
{% block js %}{% endblock %}
</body>
</html>
接着我们需要创建一个子板并继承母版,此处我们创建一个hosts.html
这样的文件.
{% extends 'base.html' %}
{% block js %} {% endblock %}
{% block css %} {% endblock %}
{% block body %}
<table>
{% for item in host %}
<tr>
<td>{{ item.hostname }}</td>
<td>{{ item.port }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
我们继续创建一个user.html
,同样也是继承base.html
模板.
{% extends 'base.html' %}
{% block js %} {% endblock %}
{% block css %} {% endblock %}
{% block body %}
<ul>
{% for item in user_list %}
<li>{{ item.username }},{{ item.salary }}</li>
{% endfor %}
</ul>
{% endblock %}
此处我们需要在urls.py
里面写好路由分发.
from django.contrib import admin
from django.urls import path
from MyWeb import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index,name="index"),
path('hosts/',views.hosts,name="hosts"),
path('user/',views.userinfo,name="user")
]
然后写好views.py
中的视图函数,默认我们返回base.html
这个页面.
from django.shortcuts import render
from django.shortcuts import HttpResponse
def index(request):
return render(request,"base.html")
def hosts(request):
hosts_list = []
for i in range(10):
temp = {'hostname':'192.168.1.'+str(i),'port':80}
hosts_list.append(temp)
return render(request,'hosts.html',{'host':hosts_list})
def userinfo(request):
user_list = []
for i in range(10):
temp = {'username': 'user' + str(i),'salary':80}
user_list.append(temp)
return render(request,'user.html',{'user_list':user_list})