使用数据库
数据库的管理,是一个网站建设的重中之重,有一个好的管理模式,方便后期的数据库扩展以及管理。
django有自带的ORM,可以方便的对数据库的表进行各种操作。
- 配置数据库
配置数据库的时候,可以直接在配置文件中,写入数据库的联接信息。
但是我选择通过文本文件的形式,配置数据库
修改xxx/settings.py中的 DATABASES
其中read_default_file就是你的数据库文件路径
然后创建文件 xxx/database_conf/xxx.cnfDATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': 'xxx/database_conf/xxx.cnf', }, } }
[client] database = xxx user = xxx password = 111111 default-character-set = utf8
- 在数据库中创建用户表
表名:users
字段:user_name,password - 编写映射模型
在xxx_1/models/model.py编写from django.db import models # Create your models here. class User(models.Model): user_name = models.CharField(max_length=50) password = models.CharField(max_length=255) class Meta: app_label = 'test_app' db_table = 'users'
- 添加模型注册
编辑xxx_1/models/init.pyfrom .model import *
- 修改你的视图文件
修改xxx_1/views/view.pyfrom django.http import HttpResponse from django.shortcuts import render, render_to_response # Create your views here. from test_app.models.user_models import User def index(request): context = {'user_count': User.objects.count()} return render(request, 'login.html', context)
- 修改html文件
用户数量:{{ user_count }}
- 启动并访问你的项目: 127.0.0.1:8000/xxx_1/index