返回顶部

纯手撸 Django web 框架实现文章上传

 纯手撸 Django web 框架实现文章上传

在上面一节创建web网站基础上增加文章上传的功能

  • 添加模型
  • 从管理后台上传数据
  • 优化显示字段

操作步骤

#创建Django环境
django-admin startproject mysite
cd mysite
python manage.py  startapp myweb


#建立默认的admin数据模型[models.py],并访问admin页面[admin.py] 
#修改settings.py
1、添加myblog至
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap4',
    'myweb'
]
1、修改数据库地址【配置引擎、数据库、地址、端口号、用户、密码】
2、修改语言、时区
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = True

mysql> create database django;


#同步数据
#python manage.py migrate

#建立管理页面的用户密码
python manage.py createsuperuser



# 运行服务
python manage.py  runserver 0.0.0.0:8080


#访问地址
#http://127.0.0.1:8080/admin/

#创建模型
#参考: https://docs.djangoproject.com/zh-hans/4.1/intro/tutorial02
#在admin.py 注册model

#更新model ,并同步数据
#Python manage.py makemigrations
#python manage.py migrate

 

创建项目及应用

#创建Django环境
django-admin startproject mysite
cd mysite
python manage.py  startapp myweb

 

部署安装数据库

安装docker


#cat  > init.sh
#!/bin/bash
##################################################################
#Auth: wei
##################################################################
Docker_Install () {
    # step 1: 安装必要的一些系统工具
    sudo yum install -y yum-utils device-mapper-persistent-data lvm2 lrzsz curl telnet tcpdump tree vim  lrzsz  wget  iotop  lsof
    # Step 2: 添加软件源信息
    sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    # Step 3
    sudo sed -i 's+download.docker.com+mirrors.aliyun.com/docker-ce+' /etc/yum.repos.d/docker-ce.repo
    # Step 4: 更新并安装Docker-CE
    sudo yum makecache fast
    sudo yum -y install docker-ce
    # Step 4: 开启Docker服务
    sudo service docker start
cat >  /etc/docker/daemon.json <<EOF
{
    "registry-mirrors": [
    "https://docker.mirrors.ustc.edu.cn",
    "https://mirror.ccs.tencentyun.com"
    ],
    "host": [
      "tcp://0.0.0.0:2375",
      "unix:///var/run/docker.sock"
    ],
    "exec-opts": ["native.cgroupdriver=systemd"],
    "log-driver": "json-file",
    "log-opts": {
      "max-size": "500m",
      "max-file": "3"
    },
    "storage-driver": "overlay2",
    "default-ulimits": {
      "nofile": {
        "Name": "nofile",
        "Hard": 64000,
        "Soft": 64000
      }
    },
    "max-concurrent-downloads": 20,
    "max-concurrent-uploads": 20
}
EOF
systemctl daemon-reload
systemctl start docker.service
systemctl enable docker.service
}

Docker_Install

 

安装数据库 mysql 8.0.33

mysql要求8版本以上

docker pull mysql
docker volume create mysql-data
docker run -d --name=mysql-server -v mysql-data:/var/lib/mysql -p 3306:3306  -e MYSQL_ROOT_PASSWORD=123456 mysql

#连接数据库
docker exec -it mysql-server mysql -u root -p

#创建数据库
mysql> create  database django;

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, myweb, sessions
Running migrations:
  Applying myweb.0001_initial... OK

 

 

修改应用配置

建立默认的admin数据模型,并访问admin页面

创建数据库及用户密码[ >create database django ]

参考官方文档: https://docs.djangoproject.com/zh-hans/4.1/ref/settings/#databases

修改settings.py配置 【添加app,修改数据库,修改时区和语言】

数据库需要8.0以上版本

### ###   mysite/mysite/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap4',
    'myweb'
]

DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': BASE_DIR / 'db.sqlite3',
    # }
    'default': {
        'ENGINE': 'django.db.backends.mysql',   #默认
        'NAME': 'django',                       #连接的数据库
        'USER': 'root',                       #mysql用户名
        'PASSWORD': '123456',       #mysql密码
        'HOST': '10.0.0.9',         #mysql地址
        'PORT': '3306',             #mysql端口
        'CHARSET': 'utf8'           #编码
    }
}



# LANGUAGE_CODE = 'en-us'
# TIME_ZONE = 'UTC'

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'



### ###  mysite/mysite/__init__.py
#pip install pymysql

import pymysql
pymysql.install_as_MySQLdb()


#需要运行迁移数据 以更改管理员用户名和密码
python manage.py migrate

 

报错"raise RuntimeError"

报错信息为: data = sha2_rsa_encrypt(conn.password, conn.salt, conn.server_public_key)

File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\pymysql\_auth.py", line 143, in sha2_rsa

_encrypt

raise RuntimeError(

RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods

PS D:\PyCharm\Python Project\mysite> pip install cryptography

Collecting cryptography

解决方法: 安装cryptography包

pip install cryptography

 

建立默认admin数据模型

编写存放应用的数据模型,

官方文档: https://docs.djangoproject.com/zh-hans/4.1/intro/tutorial02/

### ### mysite/myweb/models.py
from django.db import models

# Create your models here.
class Article(models.Model):
    title = models.CharField(max_length=200.verbose_name='文章标题')
    pub_date = models.DateTimeField(verbose_name='发布日期')
    data = models.TextField(max_length=200.verbose_name='文章内容')

 

将模型注入到admin中

### ### mysite/myweb/admin.py
from django.contrib import admin

# Register your models here.
from myweb.models import Article

# 设置admin界面展示的样式
class ArticleAdmin(admin.ModelAdmin):
    list_display = ("title","pub_date","data") #只展示一列必须加上","

admin.site.register(Article,ArticleAdmin)

效果如下:

 

 

更新model 同步数据

## 更新models 再同步数据
$ Python manage.py makemigrations
Migrations for 'myweb':
  myweb\migrations\0001_initial.py
    - Create model Article


$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, myweb, sessions
Running migrations:
  Applying myweb.0001_initial... OK

 

创建管理页面的用户密码

#需要运行迁移数据 以更改管理员用户名和密码
python manage.py migrate

#编辑用户名和密码 【wei 123456】
$ python manage.py createsuperuser
Username (leave blank to use 'administrator'): wei

#创建一个超级用户来访问django 【admin  admin 123456】
$ python manage.py createsuperuser
Username (leave blank to use 'administrator'): admin
Password: 
Password (again):

 

添加app应用

### mysite/mysite/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap4',
    'myweb'                                #添加应用包括进去,使管理界面能够找到
]

 

设置DEBUG为False

### mysite/mysite/settings.py
# DEBUG = True  生产环境不可开启,设置为False
DEBUG = False

#设置DEBUG = False必须设置ALLOWED_HOSTS否则报错
ALLOWED_HOSTS = ["*"]

 

报错“CommandError:”

报错信息为:“CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.”

提示DEBUG为False时,必须设置settings.ALLOWED_HOSTS .

ALLOWED_HOSTS = [ 
        '.example.com', # Allow domain and subdomains
    '.example.com.', # Also allow FQDN and subdomains ]

或者需要设置任何用户均可以访问,那么可以这样设置:
ALLOWED_HOSTS = ['*']
 

运行

 python manage.py  runserver 0.0.0.0:8080

 

访问

http://localhost:8080/

 

http://localhost:8080/myweb

 

http://localhost:8080/admin/

 

 

 

创建文章

 

 

 

删除文章

 

 

 

 

 

 

 

 

posted @ 2023-07-23 00:07  九尾cat  阅读(48)  评论(0编辑  收藏  举报