0%

Django学习笔记

Django学习笔记

一、开发阶段

1.(settings.py)在pycharm的venv中创建django项目

创建应用(如blog)

1
python startapp blog

编辑settings.py文件,配置数据库信息(mysql),增加:

1
2
3
4
5
6
7
8
'NAME': 'blog',		# 数据库名称
'USER':'root',
'PASSWORD':'yudashuai',
'HOST':'localhost',
'PORT':'3306',

# 将os.join 修改为 Path
'DIRS': [Path(BASE_DIR, 'templates')]

在INSTALL_APPS中注册应用,增加应用名称即可。其他修改如下:

1
2
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False

2.(models.py)编写数据库模型类

在blog应用的models.py中编写具体的数据库模型类,如BlogArticles:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from django.contrib.auth.models import User
from django.db import models

# Create your models here.
from django.utils import timezone


class BlogArticles(models.Model):
title = models.CharField(max_length=300)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)

class META:
# 以publish字段逆序展示
ordering = ('-publish',)

def __str__(self):
return self.title

3.数据模型迁移:

执行python manage.py makemigrations

执行python manage.py migrate

4.创建超级管理员

python manage.py createsuperuser

5.(blog/admin.py) 将blog写入超级管理员页面

编辑blog应用下的admin.py

1
2
3
4
5
6
from django.contrib import admin

# Register your models here.
from blog.models import BlogArticles

admin.site.register(BlogArticles)

6.丰富超级管理员页面

再次编辑blog应用下的admin.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django.contrib import admin

# Register your models here.
from blog.models import BlogArticles

# 使实体的页面更加丰富
class BlogArticlesAdmin(admin.ModelAdmin):
# 展示哪些字段
list_display = ('title', 'author', )
# 页面右侧可选的过滤条件
list_filter = ('publish',)
# 页面的搜索框(括号内的字段表示可以通过它们搜索到结果)
search_fields = ('title', 'body')
# 显示外键的详细信息
raw_id_fields = ('author',)
# 若返回时区异常,则在settings.py中修改:
# TIME_ZONE = 'Asia/Shanghai'
# USE_TZ = False
date_hierarchy = 'publish'
ordering = ['-publish', 'author']

admin.site.register(BlogArticles, BlogArticlesAdmin)

7.进入blog/views.py模块!开始与数据库交互

urls.py拦截访问请求,解析url并匹配path ==》到达views.py,views.py告诉你具体应该去哪个页面,并把处理后的数据传给静态页面

  1. 编写views
1
2
3
4
5
6
7
8
9
from django.shortcuts import render

# Create your views here.
from blog.models import BlogArticle


def blog_title(request):
blogs = BlogArticle.objects.all()
return render(request, 'blog/titles.html', {'blogs':blogs})
  1. 编写urls

    主urls:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    """re_blog URL Configuration

    The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
    Examples:
    Function views
    1. Add an import: from my_app import views
    2. Add a URL to urlpatterns: path('', views.home, name='home')
    Class-based views
    1. Add an import: from other_app.views import Home
    2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
    Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
    """
    from django.contrib import admin
    from django.urls import path, include

    urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
    ]

    子urls:

    1
    2
    3
    4
    5
    6
    7
    from django.urls import path

    from blog import views

    urlpatterns = [
    path('', views.blog_title, name='blog_title'),
    ]

8.把所有静态文件都放到指定的目录中,在settings.py的最后添加下面的代码:

在根目录下新建static文件夹

1
2
3
STATICFILES_DIRS = (
Path(BASE_DIR, 'static'),
)

上传文件的路径,在settings.py最后加:

1
2
# 上传文件的目录
MEDIA_ROOT = Path(BASE_DIR, 'media')

9.编写登录功能

(1) 自定义登录功能

(2)调用django登录功能(减少了编写view的需求)

备注:% url ‘account:user_login’ % 中,account是应用名称,user_login是url的名称,如:


二、 生产环境部署

(centos+uwsgi+nginx+mysql)

开启django时,使用0.0.0.0:xxxx,作为ip和端口例如:

python manage.py runserver 0.0.0.0:9000

然后在settings里修改ALLOWED_HOSTS = [],

改为**ALLOWED_HOSTS = [‘*‘,]**,注意不要漏掉“,”。

其他机器就可以通过这台机器的ip和端口号访问django了。


三、web开发技巧

1.上传图片后立即预览

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
<head>
<title>html5上传后立即显示</title>
<script type="text/javascript">
function ProcessFile(e) {
var file = document.getElementById('file').files[0];
if (file) {
var reader = new FileReader();
reader.onload = function (event) {
var txt = event.target.result;

var img = document.createElement("img");
img.src = txt;//将图片base64字符串赋值给img的src
// console.log(txt);
document.getElementById("result").appendChild(img);
};
}
reader.readAsDataURL(file);
}

function contentLoaded() {
document.getElementById('file').addEventListener('change',
ProcessFile, false);
}

window.addEventListener("DOMContentLoaded", contentLoaded, false);
</script>
</head>
<body>
请选取一个图像文件: <input type="file" id="file" name="file"/>
<div id="result"></div>
<div><img src="1.jpg"></div>
</body>
</html>