欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Django千峰教育笔记(2)

程序员文章站 2022-07-05 17:11:28
...

1. Django 模板(templates)

Django千峰教育笔记(2)

2.反向解析

Django千峰教育笔记(2)

3.模板继承

Django千峰教育笔记(2)
base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #header{
            width:100%;
            height:100px;
            background-color:red;
            }
        #footer{
            width:100%;
            height:100px;
            background-color:blue;
            }

    </style>
</head>

<body>
    <div id="header">header</div>

    <div id="main">
        {% block main %}

        {% endblock main %}
		{% block main2 %}

        {% endblock main2 %}
    </div>

    <div id="footer">footer</div>

</body>
</html>

main.html

{% extends 'myapp2/base.html' %}

{% block main  %}

    <h1>欢迎使用Django</h1>
    
{% endblock main  %}

{% block main2  %}

    <h1>再次欢迎使用Django</h1>
    
{% endblock main2  %}

4.HTML 转义

Django千峰教育笔记(2)

view.py

def code (request,p1):
    return render(request,"myapp2/good.html",{"num":p1,"code":"<h1> 努力学习</h1>"})

.html

<body>
# 直接将接受到的code当成普通字符串渲染(注释方式不对)
	{{code}}
	{{code|escape}}
	{% autoescape on%} # 自动转义 开
	{{code}}
	{% endescape %}

# 将接收到的 code 当成HTML的代码渲染 (注释方式不对)
	{{code|safe}}
	
	{% autoescape off%} # 自动转义 开
	{{code}}
	{% endescape %}

</body>

5 静态文件

Django千峰教育笔记(2)

{% load static from staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="{% static 'myAPP/css/style.css'%}"/>
    <script type="text/javascript" src="/static/myAPP/js/sunck.js"></script>
</head>
<body>
    <h1> 万般测试,方能下比如神</h1>
    <img src="/static/myAPP/js/1.png">
    <img src="{% static 'myAPP/img/1.png'%}">
</body>
</html>

6 中间件

Django千峰教育笔记(2)

from django.utils.deprecation import MiddlewareMixin
class myMiddle(MiddlewareMixin):
    def process_request(self,request):
        print("get参数:",request.GET.get("a"))

Django千峰教育笔记(2)

7 上传图片

Django千峰教育笔记(2)
views.py

import os
from django.conf import settings
from django.shortcuts import render
def upfile(request):
    return  render(request,'myAPP/upflie.html')

def savefile(request):
    if request.method == "POST":
        f = request.FILES["file"]
        # 合成存储路径,文件在服务器端的路径
        filPath = os.path.join(settings.MDEIA_ROOT,f.name)

        with open(filPath,'wb') as fp:
            for info in f.chunks():  # 防止文件过大分段上传
                fp.write(info)
        return HttpResponse("上传成功")
    else:
        return HttpResponse("上传失败")

urls.py

urlpatterns = [
    url(r'^index/$', views.index),
    url(r'^upfile/$',views.upfile),
    url(r'^savefile/$',views.savefile)
    ]

upfile.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传</title>
</head>
<body>
    <form method="post" action="/savefile" enctype="multipart/form-data">
        {% scrf_token %}
        <input type="file" name="file"/>
        <input type="submit" value="上传"/>
    </form>

</body>
</html>

8 分页

paginator对象和page对象的关系
Django千峰教育笔记(2)studentpage.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        {% for stu in students %}
        <li>
            {{stu.sname}}---{{stu.sgrade}}
        </li>

        {% endfor %}
    </ul>
<!--  页码  -->
    <ul>
        {% for index in students.paginator.page_range %}
            <li>
                <a href="/studentpage/{{index}}">index</a>
            </li>
        {% endfor %}
    </ul>
</body>
</html>

view.py

def studentpage(request,pageid):
    # 获得所有学生列表
    allList = Students.objects.all()
    # 设置每页显示几条信息
    paginator = Paginator(allList,6)
    # 当前页的列表
    page = paginator.page(pageid)

    return render(request,"myAPP/studentpage.html",{"students":page})

urls.py

url(r'^studentpage/(\d+)/$', views.studentpage),

Django千峰教育笔记(2)

9 Ajax

ajaxstudent.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="/static/myAPP/js/jquery-3.0.0.min.js"></script>
</head>
<body>
    <h1>学生信息列表</h1>
    <button id="btn"></button>
    <script type="text/javascript" src="/static/myAPP/js/sunck.js"></script>
</body>
</html>

urls.py

	url(r'^ajaxstudents/$', views.ajaxstudents),
    url(r'^studentsinfo/$', views.studentsinfo),

views.py

ef ajaxstudents(request):
    return render(request, "myAPP/ajaxstudents.html" )

from django.http import JsonResponse
def studentsinfo(request):
    stus = Students.objects.all()
    list= []
    for stu in stus:
        list.append([stu.sname,stu.sage])
    return JsonResponse({"data":list})

10 富文本

安装富文本插件 pip install python-tinymce

在站点中使用富文本
Django千峰教育笔记(2)

  1. 配置setting.py
INSTALLED_APPS  ={

#  添加一行
'tinymce'
}
...

# 富文本
TINYMCE_DEFAULT_CONFIG = {
    'theme':'advanced',
    'width':600,
    'height':400,
}
  1. 创建一个模型类
from tinymce.model import  HTMLFile
class Text(models.Model):
    str = HTMLFile
  1. 配置站点
from django.contrib import admin

# Register your models here.


from .models import Text
admin.site.register(Text)

在自定义视图中使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>富文本</title>
    <script type="text/javascript" src="/static/tiny-mce/tiny_mce.js"></script>
    <script type="text/javascript" >
        tinyMCE.init({
            'mode':'textareas',
            'theme':'advanced',
            'width':800,
            'height':600,
        })
    </script>
</head>
<body>
    <form>
        <textarea name="str"> sunck  is a good man  </textarea>
    </form>
</body>

11 celery

Django千峰教育笔记(2)
Celery - 分布式任务队列

  1. 配置setting.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myAPP',
    'tinymce',
    'djcelery',
]
... 
# celery
import djcelery
djcelery.setup_loader() # 初始化
# redis   密码/ip地址:端口号
BROKER_URL = 'redis://:aaa@qq.com:6379/0'
CELERT_IMPORTS=('myAPP/task')  # 耗时操作的python文件

celery.py

import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTING_MODULE','whthas_home.settings')

app = Celery('portal')

app.config_from_object('django.conf:settings')

app.autodiscover_tasks(lambda :settings.INSTALLED_APPS)

@app.task(bind=True)
def debug_task(self):
    print('Request:{o!r}'.format(self.request))

peoject/init.py

import pymysql
pymysql.install_as_MySQLdb()

from .celery import app as celery_app
相关标签: Django