二 、django models基本使用

django 本身提供了非常强大易使用的ORM组件,并且支持多种数据库,如sqllite,mysql,progressSql,Oracle等

1、定义数据,我们使用sqlit数据库

在models.py模块中定义表和字段格式:

from django.db import models

# Create your models here.

class Userinfo(models.Model):
    '''定义数据库表,类名就是表名,max_length相当于varchar,字段格式定义'''
    username = models.CharField(max_length=32,null=True)
    password = models.CharField(max_length=32,null=True)

在setting.py文件中的列表 INSTALLED_APPS 加入app包的名字,让django能够找到他

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bbsAPP',
]

生成同步纪录

python manage.py makemigrations   
D:\project\chaoDjango>python manage.py makemigrations
Migrations for 'bbsAPP':
  bbsAPP\migrations\0001_initial.py
    - Create model Userinfo

开始同步:

 python manage.py migrate

这样就能让数据导数据库中
我们在sqlite中插入几条数据 ,其中的id字段是默认自增让django读取,注意写完数据要点箭头所指处保存数据。
在这里插入图片描述

2、在views.py中创建逻辑判断语句,来判断将在页面输出什么内容

from django.shortcuts import render,HttpResponse,redirect
from bbsAPP import models
# Create your views here.
def login(request):
    a = ['hello django','liaochao']
    if request.method == 'GET':
        #将userinfo中所有的数据拿过来
        obj_list = models.Userinfo.objects.all()
        # obj_list = models.Userinfo.objects.filter(username='liaochao')  #拿具体某个用户的数据
        for obj in obj_list:
            print('username-->',obj.username)
            print('password-->',obj.password)
    # return HttpResponse("登录")
    return  render(request,'login.html',locals())

3.在templates下面的html中 写入需要展示的内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>liaochao's Django</title>
</head>
<body>
    <!-- html只也可以直接传入list并且切片-->
    <h1> {{ a.0 }} </h1>
    <h1> {{ obj_list }} </h1>

    {%  for items in obj_list %}
        <span>{{ items.username }}</span>
        <span>{{ items.password }}</span>
    {% endfor %}
</body>
</html>

效果展示:

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值