fengwenzhee

一、

(1)使用idea生成一个python项目,安装Django框架:

pip install django==1.8.2

(2)初始化项目:

django-admin startproject xxx //xxx为项目名称

 

(3)初始化应用:

python manage.py startapp xxx //xxx为应用名称

 

(4)在settings.py中注册刚生成的应用:

INSTALLED_APPS = (
    \'django.contrib.admin\',
    \'django.contrib.auth\',
    \'django.contrib.contenttypes\',
    \'django.contrib.sessions\',
    \'django.contrib.messages\',
    \'django.contrib.staticfiles\',
    \'home\', //这是我们刚生成的应用
)

 

(5)测试项目是否可以正常启动:

python manage.py runserver IP:端口

浏览器访问如下:

 

 PS:Django默认使用的是sqlite3数据库,可以根据model生成数据库表,生成的文件在migrations目录下:

(1)我们先在model中写一个测试类:

from django.db import models
# Create your models here.
#学生类
class StuUser(models.Model):
    \'\'\'学生模型类\'\'\'
    #照片
    studentName = models.CharField(max_length=255)
    studentNumber = models.CharField(max_length=255)
    picture = models.CharField(max_length=255)
    phoneNumber = models.CharField(max_length=255)
    address = models.CharField(max_length=255)
    createDate = models.DateTimeField()
    updateDate = models.DateTimeField()

(2)终端运行如下指令:

python manage.py makemigrations

运行后可以发现migrations目录下多了一个0001_initial.py文件,就是我们model的迁移文件:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name=\'StuUser\',
            fields=[
                (\'id\', models.AutoField(verbose_name=\'ID\', primary_key=True, serialize=False, auto_created=True)),
                (\'studentName\', models.CharField(max_length=255)),
                (\'studentNumber\', models.CharField(max_length=255)),
                (\'picture\', models.CharField(max_length=255)),
                (\'phoneNumber\', models.CharField(max_length=255)),
                (\'address\', models.CharField(max_length=255)),
                (\'createDate\', models.DateTimeField()),
                (\'updateDate\', models.DateTimeField()),
            ],
        ),
    ]

然后再运行如下指令:

 python manage.py migrate

此时就会生成一个db.sqlite3文件,这是一个小型数据库,我们需要安装一个工具才能有可视化数据库界面,由于项目使用的是mysql数据库,后续需要更改对应数据库配置,此处不过多赘述

二、django整合mysql

(1)django完成视图搭建:(注意项目结构,我使用的idea生成的项目,需要删除一层,使项目结构如下:)

 

 其中homework为项目,home是我们运行如下指令初始化的应用:(一定要注意)

 python manage.py startapp home

 

首先,我们在settings.py配置文件的TEMPLATES->DIRS中添加如下代码:(指定模板路径)

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

应用中新建对应路径的文件夹做为我们的view模板渲染层,进行前后端分离的项目就不需要这些操作了

 

 

 

home应用中的urls.py配置路由(默认生成的home应用没有urls.py,从项目homework中复制一份):

from django.conf.urls import  url
from home import views
urlpatterns = [
url(r\'^index$\',views.index),#首页
]

home应用中的views.py文件中配置视图:

from django.shortcuts import render

# Create your views here.
def index(request):
    \'\'\'首页\'\'\'
    return render(request,\'home/index.html\')

项目的urls.py中引入应用的路由:

urlpatterns = [
    url(r\'^admin/\', include(admin.site.urls)),
    url(r\'^\', include(\'home.urls\')),
]

模板中新建index.html

 

 index.html内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>首页</h1>
</body>
</html>

 

然后运行

 manage.py runserver 127.0.0.1:8080

 

 这样一个路由就配置好了

PS:简单介绍以下Django路由的原理,如下图所示:()

 

自定义404页面:

settings.py修改如下配置:

DEBUG = False

ALLOWED_HOSTS = [\'127.0.0.1\']

templates下新建404.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>页面找不到</h1>
</body>
</html>

 返回JSON数据:

 views.py

from django.shortcuts import render
from home import models
from django.shortcuts import HttpResponse
import json
# Create your views here.
def index_json(request):
    result = {"password": \'111\', "encrypt": \'222\'}
    return HttpResponse(json.dumps(result))

urls.py

from django.conf.urls import  url
from home import views
urlpatterns = [
    url(r\'^index$\',views.index),#首页
    url(r\'^index_json$\',views.index_json),#首页
 ]

浏览器访问:localhost:8080/index_json

 

 

 

(2)配置mysql数据库(settings.py文件中修改数据库配置):

DATABASES = {
    \'default\': {
        \'ENGINE\': \'django.db.backends.mysql\',
        \'NAME\': \'stu_user\',//数据库名称
        \'USER\': \'root\',
        \'PASSWORD\': \'root\',
        \'HOST\': \'localhost\',
        \'PORT\': \'3306\',
    }
}

项目中新建model后,可以同步数据库表,具体指令如下(此指令只能同步Django内置表):

python manage.py syncdb

  

 

 

 其中,django_migrations是记录数据库迁移log日志,使用如下命令也可实现(会将自己的app model同步到数据库 如果想要修改表结构,修改

model后执行如下指令无法同步,请查看django_migrations中的相关日志,删除对应app的日志再执行即可):

python manage.py makemigrations
python manage.py migrate

PS:一对多模型实现:

models.py

from django.db import models
# Create your models here.
#学生类
class stu_user(models.Model):
    \'\'\'学生模型类\'\'\'
    #照片
    student_name = models.CharField(max_length=255)
    student_number = models.CharField(max_length=255)
    picture = models.CharField(max_length=255)
    phone_number = models.CharField(max_length=255)
    address = models.CharField(max_length=255)
    create_date = models.DateTimeField()
    update_date = models.DateTimeField()
#教育经历类
class stu_experience(models.Model):
    \'\'\'学生模型类\'\'\'
    #照片
    user = models.ForeignKey("stu_user", to_field=\'id\', on_delete=models.CASCADE)
    begin_date = models.DateTimeField()
    end_date = models.DateTimeField()
    school = models.CharField(max_length=255)
    level = models.IntegerField()

 

 

 

views.py中测试新增数据:

from django.shortcuts import render
from datetime import date
from home import models
# Create your views here.
def index(request):
    \'\'\'首页\'\'\'
    book = models.StuUser(
        studentName = \'冯文哲\'
    )
    book.save()
    return render(request,\'home/index.html\')

 一对多查询,并格式化时间后json输出:

models.py中定义如下类:

class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj,datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self,obj)

views.py中定义路由业务处理:

def one_to_many(request):
    print(request)
    student = models.stu_user.objects.get(id=\'1\')
    result = []
    exp = student.stu_experience_set.all()
    for item in exp:
        result.append(model_to_dict(item))#对象转字典
    print(type(serializers.serialize(\'json\',exp)))
    print(type(json.loads(serializers.serialize(\'json\',exp))))
    student = model_to_dict(student)#对象转字典
    res = {\'student\':student,\'exp\':result}#字典类型
    print(type(res))
    return HttpResponse(json.dumps(res,cls=models.DateEncoder))#格式化日期,json输出

 

分类:

技术点:

相关文章: