博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django实例(4):一对多外键关联
阅读量:5742 次
发布时间:2019-06-18

本文共 8619 字,大约阅读时间需要 28 分钟。

程序目录

Project-->urls.py

from django.contrib import admin
from django.conf.urls import url,include
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^cmdb/',include('app01.urls')),
    # url(r'^monitor/',include('app02.urls')),
]

 

 

App01--->urls.py

from django.contrib import admin

from django.conf.urls import url
from app01 import views
urlpatterns = [
    url(r'^login/', views.login),
    url(r'^index/', views.index),
    url(r'^user_info/', views.user_info),
    url(r'^userdetail-(?P<nid>\d+)/', views.user_detail),
    url(r'^userdel-(?P<nid>\d+)/', views.user_del),
    url(r'^useredit-(?P<nid>\d+)/', views.user_edit),
    url(r'^orm/', views.orm),
]

 

 

App01--->views.py

from django.shortcuts import render,HttpResponse,redirect

from app01 import models
def orm(reqbuest):
    # 创建表
    # models.UserInfo.objects.create(username='root',password='123')
    # dic={'username':'eric','password':'666666'}
    # models.UserInfo.objects.create(**dic)
    # 查询表
    # result= models.UserInfo.objects.all()
    #删除
    # models.UserInfo.objects.filter(id='2').delete()
    # 更改
    # models.UserInfo.objects.filter(id='3').update(password='666666')
    #外键 一对多
    user_list=models.UserInfo.objects.create(
        username='lucy',
        password='12345',
        email='sdssf@126.com',
        test="sss",
        # user_group=models.UserGroup.objects.filter(id=1).first()
        user_group_id='1',
    )
    return HttpResponse('orm')
def login(request):
    models.UserGroup.objects.create(caption="BA")
    # models.UserGroup.objects.filter(uid='1').update(caption="CEO")  这种方法不会更新uptime
    # obj=models.UserGroup.objects.filter(uid='1').first() 更新uptime用这种方法
    # obj.caption="DBA"
    # obj.save()
    if request.method=="GET":
        return render(request,'login.html')
    elif request.method=="POST":
        # 数据库中执行 select * from user where username='x' and password='x'
        u=request.POST.get('user')
        p=request.POST.get('pwd')
        obj= models.UserInfo.objects.filter(username=u,password=p).first()
        # count = models.UserInfo.objects.filter(username=u, password=p).count()
        if obj:
            return redirect('/cmdb/index/')
        else:
            return render(request,'login.html')
    else:
        return redirect('/index/')
def index(request):
    return render(request,'index.html')
def user_info(request):
    if request.method=="GET":
        user_list= models.UserInfo.objects.all()
        group_list=models.UserGroup.objects.all()
        # for row in user_list:
        #     print(row.id,row.user_group.uid)
        #     print(row.user_group.caption)
        # print(user_list.query)
        # QuerySet [obj(id,username,email,user_group_id,user_group(uid,caption)),obj]
        return render(request,'user_info.html',{
'User_List':user_list,'Group_List':group_list})
    elif request.method=="POST":
        u=request.POST.get('user')
        p=request.POST.get('pwd')
        models.UserInfo.objects.create(username=u,password=p)
        return redirect('/cmdb/user_info/')
def user_detail(request,nid):
    obj=models.UserInfo.objects.filter(id=nid).first()
    # models.UserInfo.objects.get(id=nid) 如果没有数据会报错
    return render(request,'user_detail.html',{
'OBJ':obj})
def user_del(request,nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/cmdb/user_info/')
def user_edit(request,nid):
    if request.method=="GET":
        obj=models.UserInfo.objects.filter(id=nid).first()
        return render(request,'user_edit.html',{
'OBJ':obj})
    elif request.method=="POST":
        nid=request.POST.get('id')
        u=request.POST.get('username')
        p=request.POST.get('password')
        models.UserInfo.objects.filter(id=nid).update(username=u,password=p)
        return redirect('/cmdb/user_info/')

 

 

App01-->models.py

from django.db import models

#app01_userinfo
class UserInfo(models.Model):
    # id列,自增,主键
    # 用户名列,字符串类型,指定长度
    # 数据类型:数字 时间 二进制
    username=models.CharField(max_length=64,blank=True,verbose_name="姓名")
    password=models.CharField(max_length=60,error_messages={
'required':'密码'})
    email=models.CharField(max_length=32,help_text="邮件")
    test=models.GenericIPAddressField(max_length=32,null=True)
    # gender=models.CharField(max_length=64,null=True)
    user_type_choice=(
        (1,'super user'),
        (2,'normal user'),
        (3,'normal normal user'),
    )
    user_type_id=models.IntegerField(choices=user_type_choice,default=1)
    #user_group_id 数字
    user_group=models.ForeignKey("UserGroup",to_field='uid',default=1,on_delete=models.CASCADE)
    # 报 __init__() missing 1 required positional argument: 'on_delete'
    # 在外键值的后面加上 on_delete = models.CASCADE
    # user_group是UserGroup的一个对象
    # uer_list=models.UserInfo.objects.all()
    # for row in uer_list:
    #     print(row.user_group_id)
    #     print(row.user_group.uid)
    #     print(row.user_group.caption)
class UserGroup(models.Model):
    uid=models.AutoField(primary_key=True)
    caption=models.CharField(max_length=64)
    ctime=models.DateTimeField(auto_now_add=True,null=True)
    uptime=models.DateTimeField(auto_now=True,null=True)

 

 

App01-->admin.py

from django.contrib import admin

# Register your models here.
from app01 import models
admin.site.register(models.UserInfo)
# 在app的admin.py加上这两句具有admin功能

 

 

Templates-->login.html

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/cmdb/login/" method="post" enctype="multipart/form-data">
        <p>
            <input type="text" name="user" placeholder="用户名">
        </p>
        <p>
            <input type="password" name="pwd" placeholder="密码">
        </p>
        <p>
            <input type="submit" value="提交">
        </p>
    </form>
</body>
</html>

 

 

Templates-->index.html

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin:0;
        }
        .menu{
            display: block;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div style="height: 48px;background-color: black;color: white;">
        
    </div>
    <div>
        <div style="position: absolute;top:48px;bottom: 0;left: 0;width: 500px;background-color: brown">
            <a class="menu" href="/cmdb/user_info/">用户管理</a>
            <a class="menu" href="/cmdb/user_group/">用户组管理</a>
        </div>
        <div style="position: absolute;top:48px;left:520px;bottom: 0;right: 0;overflow: auto">
            
        </div>
    </div>
    
</body>
</html>

 

Templates-->user_info.html

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin:0;
        }
        .menu{
            display: block;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div style="height: 48px;background-color: black;color: white;">
    </div>
    <div>
        <div style="position: absolute;top:48px;bottom: 0;left: 0;width: 500px;background-color: brown">
            <a class="menu" href="/cmdb/user_info/">用户管理</a>
            <a class="menu" href="/cmdb/user_group/">用户组管理</a>
        </div>
        <div style="position: absolute;top:48px;left: 520px;bottom: 0;right: 0;overflow: auto">
            <h3>添加用户</h3>
            <form method="POST" action="/cmdb/user_info/">
                <input type="text" name="user">
                <input type="text" name="pwd">
                <select name="group_id">
                    {% for item in Group_List %}
                        <option value="{
{ item.uid }}">{
{ item.caption }}</option>
                    {% endfor %}
                </select>
                <input type="submit" value="添加">
            </form>
            <h3>用户列表</h3>
            <ul>
                {% for row in User_List %}
                    <li><a href="/cmdb/userdetail-{
{ row.id }}/">{
{ row.username }}</a> |
                        <span>用户组:{
{ row.user_group.caption }}</span> |
                        <a href="/cmdb/userdel-{
{ row.id }}/">删除</a> |
                        <a href="/cmdb/useredit-{
{ row.id }}/">编辑</a> |
                    </li>
                {% endfor %}
            </ul>
            <ul>
            </ul>
        </div>
    </div>
</body>
</html>

 

 

Templates-->user_detail.html

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin:0;
        }
        .menu{
            display: block;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div style="height: 48px;background-color: black;color: white;">
    </div>
    <div>
        <div style="position: absolute;top:48px;bottom: 0;left: 0;width: 500px;background-color: brown">
            <a class="menu" href="/cmdb/user_info/">用户管理</a>
            <a class="menu" href="/cmdb/user_group/">用户组管理</a>
        </div>
        <div style="position: absolute;top:48px;left: 520px;bottom: 0;right: 0;overflow: auto">
            <h1>用户详细信息</h1>
            <h5>id: {
{ OBJ.id }}</h5>
            <h5>username: {
{ OBJ.username }}</h5>
            <h5>password: {
{ OBJ.password }}</h5>
        </div>
    </div>
</body>

 

 

 

Templates-->user_edit.html

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin:0;
        }
        .menu{
            display: block;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div style="height: 48px;background-color: black;color: white;">
    </div>
    <div>
        <div style="position: absolute;top:48px;bottom: 0;left: 0;width: 500px;background-color: brown">
            <a class="menu" href="/cmdb/user_info/">用户管理</a>
            <a class="menu" href="/cmdb/user_group/">用户组管理</a>
{#            <a class="menu"></a>#}
        </div>
        <div style="position: absolute;top:48px;left:520px;bottom: 0;right: 0;overflow: auto">
            <h1>编辑用户</h1>
                <form method="post" action="/cmdb/useredit-{
{ OBJ.id }}/">
                    <input style="display: none" type="text" name="id" value="{
{ OBJ.id }}"/>
                    <input type="text" name="username" value="{
{ OBJ.username }}"/>
                    <input type="text" name="password" value="{
{ OBJ.password }}"/>
                    <input type="submit" value="提交">
                </form>
        </div>
    </div>
</body>
</html>

转载于:https://www.cnblogs.com/leiwenbin627/p/10995351.html

你可能感兴趣的文章
分享一段ios数据库代码,包括对表的创建、升级、增删查改
查看>>
如何书写高质量的jQuery代码
查看>>
Activity的生命周期整理
查看>>
【记录】JS toUpperCase toLowerCase 大写字母/小写字母转换
查看>>
在 Linux 系统中安装Load Generator ,并在windows 调用
查看>>
Visifire charts ToolBar
查看>>
Mysql查询
查看>>
数据传输流程和socket简单操作
查看>>
ProbS CF matlab源代码(二分系统)(原创作品,转载注明出处,谢谢!)
查看>>
OC中KVC的注意点
查看>>
JQ入门(至回调函数)
查看>>
【洛天依】几首歌的翻唱(无伴奏)
查看>>
OpenSSL初瞻及本系列的博文的缘由
查看>>
ISO8583接口的详细资料
查看>>
tmux不自动加载配置文件.tmux.conf
查看>>
经验分享:JavaScript小技巧
查看>>
[MOSEK] Stupid things when using mosek
查看>>
程序实例---栈的顺序实现和链式实现
查看>>
服务的使用
查看>>
Oracle 用户与模式
查看>>