django学习笔记---使用orm实现用户的增删改查

Django练习的基本框架

django学习笔记---使用orm实现用户的增删改查_第1张图片

主程序url.py

from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'app1/',include("app01.urls")),   # 路由分级
    url(r'app2/',include("app02.urls")),
]


app01 下

admin.py

from app01 import models

admin.site.register(models.UserInfo)
admin.site.register(models.UserGroup)

在主程序url.py写上admin的url,这样在django.admin中就有

django学习笔记---使用orm实现用户的增删改查_第2张图片

url.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^login/', views.login),# 看视频说,这个login/ 和login.html中的form表单的login/要么都加,要么都不加,不过貌似现在只能都加
    url(r'^orm/', views.orm),
    url(r'^index1/',views.index1),
    url(r'^user_info/',views.user_info),
    url(r'^userInfoDetail-(?P\d+)/',views.userInfoDetail),
    url(r'^userInfoDel-(?P\d+)/',views.userInfoDel),
    url(r'^useredit-(?P\d+)/',views.userInfoEdit),
]

models.py  用于创建表

from django.db import models

# Create your models here.

class UserGroup(models.Model):
    uid = models.AutoField(primary_key=True)   # 设为自增,就要设为主键
    caption = models.CharField(max_length=32)
    ctime = models.DateTimeField(auto_now_add=True,null=True)   # 创建数据的时候,这个就会自动创建,比如在views.login
    uptime = models.DateTimeField(auto_now=True, null=True)     # 记录更新的时间

class UserInfo(models.Model):
    name = models.CharField(max_length=16)
    pwd = models.CharField(max_length=32)
    email = models.EmailField(max_length=20)   # EmailField保证在django.admin时提交数据的格式
    ip4 = models.GenericIPAddressField(editable=False)   # IP格式 如果不写null=True,就要自动在终端写
    ip6 = models.GenericIPAddressField()   # IP格式

    # 用于关联UserGroup表,关联的键为‘uid',在user_info中生成user_group_id的表。同时可以获取user_group对象,user_group.uid / user_group_caption
    user_group = models.ForeignKey('UserGroup',to_field='uid',default=1)

    # 作用1.一般不会变更的属性,比如外键,那么就可以像user_type_choices存储在内存中,避免连表查询,数据库一般很少进行连表查询 2.在sql表中存储的还是数字,但是在django.admin中就有超级/普通/低级选项
    user_type_choices = (
        (1,'超级用户'),
        (2,'普通用户'),
        (1,'低级用户'),
    )
    user_type_id = models.IntegerField(choices=user_type_choices,default=1)

views.py   业务处理

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.
#先导入models
from app01 import models

def login(request):
    # models.UserGroup.objects.create(caption='t1')
    # models.UserGroup.objects.filter(uid=1).update(caption='t2')
    # obj = models.UserGroup.objects.filter(uid=1).first()
    # obj.caption = 't3'
    # obj.save()
    userInfo = models.UserInfo.objects.all()
    for row in userInfo:
        print(row.user_group.caption)
    return HttpResponse('App01')

def index1(request):
    return render(request,'index1.html')

def orm(request):
    # 增1 推荐这种
    # models.UserInfo.objects.create(name='Tom',pwd='123')
    # dic1 = {'name':"John",'pwd':111}
    # models.UserInfo.objects.create(**dic1)
    #增2
    # obj = models.UserInfo(name="alex",pwd=222)     # 或者先创建一个实例 obj = models.UserInfo() obj.name='alex' obj.pwd=222 obj.save()
    # obj.save()

    #查
    # obj = models.UserInfo.objects.all()
    # for ele in obj:
    #     print(ele.name,ele.pwd)
    # obj1 = models.UserInfo.objects.filter(name='Tom').first()   // UserInfo object
    # print(obj1.name,obj1.pwd)

    #改
    # models.UserInfo.objects.filter(name='Tom',id=1).update(pwd='new2')

    # 删
    # models.UserInfo.objects.filter(name='John').delete()

    # 创建有外键关联的表
    models.UserInfo.objects.create(
        name="Anna",
        pwd='111',
        email='[email protected]',
        ip4='2.1.1.1',
        ip6='1.1.1.1',
        user_type_id='2',
        user_group_id=4,
    )
    return HttpResponse("ORM 202")

def user_info(request):
    if request.method == "GET":
        user_list = models.UserInfo.objects.all()
        # print(user_list.query)   // 能打印出QuerySet的具体信息
        userGroupList = models.UserGroup.objects.all()
        return render(request,'user_info.html',{'user_list':user_list,'userGroupList':userGroupList})
    # 添加功能,添加新的用户后重定向到app1/user_info页面
    elif request.method == "POST":
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        email = request.POST.get('email')
        ip4 = request.POST.get('ip4')
        ip6 = request.POST.get('ip6')
        user_type_id = request.POST.get('user_type_id')
        user_group_id = request.POST.get('user_caption')
        # print(name,pwd  )
        models.UserInfo.objects.create(name=name,pwd=pwd,email=email,ip4=ip4,ip6=ip6,user_type_id=user_type_id,user_group_id=user_group_id)
        return redirect('app1/user_info')

def userInfoDetail(request,nid):
    '''
    :param request:
    :param nid: 用户在数据库中的id号
    :return:
    '''
    userInfo = models.UserInfo.objects.filter(id=nid).first()
    print(userInfo.name)
    # print(models.UserInfo.objects.filter(id=nid).name)
    # userInfo = models.UserInfo.objects.get(id=6)   //get 直接能取到,如果不存在,直接报错,filter不存在只会返回none
    return render(request,'userInfoDetail.html',{'userInfo':userInfo})

def userInfoDel(request,nid):
    # models.UserInfo.objects.filter(id=nid).delete()
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/app1/user_info')
    # return redirect('http://www.baidu.com')

def userInfoEdit(request,nid):
    if request.method == "GET":
        userInfo = models.UserInfo.objects.filter(id=nid).first()
        return render(request,'userInfoEdit.html',{'userInfo':userInfo})
    elif request.method == "POST":
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        models.UserInfo.objects.filter(id=nid).update(name=name,pwd=pwd)
        return redirect('/app1/user_info')


template 下的各种模板

user_info.html




    
    Title
    


    
这是测试表头

添加用户

用户信息

显示页面

django学习笔记---使用orm实现用户的增删改查_第3张图片

userInfoDetail.html




    
    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title
    


    
这是测试表头

    用户信息

  • 姓名: {{ userInfo.name }}
  • 密码: {{ userInfo.pwd }}
  • 邮箱: {{ userInfo.email }}
  • ip4: {{ userInfo.ip4 }}
  • ip6: {{ userInfo.ip6 }}
  • user_type_id: {{ userInfo.user_type_id }}
  • user_group_id: {{ userInfo.user_group_id }}

点击上图的姓名后显示该用户的详细信息

django学习笔记---使用orm实现用户的增删改查_第4张图片

userInfoEdit.html




    
    Title
    


    
这是测试表头

点击编辑后显示





你可能感兴趣的:(Django学习笔记)