Django--数据管理系统

Django--数据管理系统

数据库操作:

cmd

mysql -u root -p

user sd;

show tables;

插入数据:

insert into app01_prettynum(mobile,price,level,status)values('12345678901',190,1,1);

select * from app01_prettynum;

python内对数据库的操作:

创建数据:

Import pymysql

While True,
	User = input("用户名:")
	If user.upper() == 'Q':
	break
Pwd = input("密码:")
Mobile = input("手机号:")

Conn = pymysql.connect(host="127.0.0.1", port=2206, user='root', passwd="123456", charset='utf8', db='unicom')
Cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)


Sql = "insert into admin(user,password,mobile) values(%s,%s,%s)"

Cursor.execute(sql,[user.pwd,mobile])
conn.commit()

Cursor.close()
Conn.close

运行更新数据库、运行项目:

首先安装

pip install django

查看安装位置:

pip show django

image-20250103101116150

建立、运行app01

python manage.py startapp app01

django-admin startup app01

创建数据库:

DATABASES={
'default':{
'ENGINE':'django.db.backends.mysql',
'NAME':'gzz',
'USER':'root',
'PASSWORD':'123',
'HOST':'127.0.0.1',
'PORT':'3306',
}
}

在setting.py内设置:

DATABASES={
'default':{
'ENGINE':'django.db.backends.mysql',
'NAME':'gzz',
'USER':'root',
'PASSWORD':'123',
'HOST':'127.0.0.1',
'PORT':'3306',
}
}

更新数据库、运行项目:

python manage.py makemigrations

python manage.py migrate

python manage.py r

网页代码继承:

model.PrettyNum.objects.filter(id=12)  #等于12

<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>Title</title>
</head>
<body>


{% block content %}



{% endblock %}

</body>
</html>

继承模板:

{% extends'layout.html' %}

{% blockcontent %}

<h1>首页</h1>

{% endblock %}

·继承css\JS模板··

{% block css %}

{% endblock %}

框架内代码:

搭建数据库

class PrettyNum(models.Model):
    """靓号"""
    mobile = models.CharField(verbose_name="手机号", max_length=11)
    price = models.IntegerField(verbose_name="价格", default=0)

    level_choices = (
        (1, "1级"),
        (2, "2级"),
        (3, "3级"),
        (4, "4级"),

    )
    level = models.SmallIntegerField(verbose_name="级别", choices=level_choices, default=1)

    status_choices = (
        (1, "已占用"),
        (2, "未使用"),
    )
    status = models.SmallIntegerField(verbose_name="级别", choices=status_choices, default=2)

靓号列表:

from django.core.validators import RegexValidator

from django.core.validators import ValidationError

class PrettyModelForm(forms.ModelForm):
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        # fields = ["mobile",'price','level','status']
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control rounded-3", "placeholder": field.label}

    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]

        exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号存在")
        return txt_mobile

添加 pretty add

def pretty_add(request):
    """添加靓号"""
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {"form": form})

    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    else:
        return render(request, 'pretty_add.html', {"form": form})


编辑 pretty edit

class PrettyEditModelForm(forms.ModelForm):
    # 编写手机号不可编辑
    # mobile = forms.CharField(disabled=True, label="手机号")
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        fields = ['mobile', 'price', 'level', 'status']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control rounded-3", "placeholder": field.label}

    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]

        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号存在")
        return txt_mobile
def pretty_edit(request, nid):
    row_object = models.PrettyNum.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID获取数据库编辑的哪一行数据
        form = PrettyModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {'form': form})

    form = PrettyEditModelForm(data=request.POST, instance=row_object)  # 对当前行修改数据
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_edit.html', {'form': form})

删除 pretty delete

def pretty_delete(request,nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')

手机号

正则表达式 :

    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

html网页代码:

pretty list:

{% extends 'layout.html' %}

{% block content %}

<div class="container">
    <div style="margin-bottom: 10px">
        <a class="btn btn-success" href="/pretty/add/">新建靓号</a>
    </div>
    <table class="table table-striped table-sm">
        <div class="panel-heading"><h5>靓号列表</h5></div>
        <thead>
        <tr>
            <th scope="col">ID</th>
            <th scope="col">号码</th>
            <th scope="col">价格</th>
            <th scope="col">级别</th>
            <th scope="col">状态</th>
            <th scope="col">操作</th>
        </tr>
        </thead>
        <tbody>
        {% for obj in queryset %}
        <tr>
            <th>{{ obj.id }}</th>
            <td>{{ obj.mobile }}</td>
            <td>{{ obj.price }}</td>
            <td>{{ obj.get_level_display }}</td>
            <td>{{ obj.get_status_display }}</td>
            <td>
                <a class="btn btn-primary btn-xs" href="/pretty/{{ obj.id }}/edit/">编辑</a>
                <a class="btn btn-danger btn-xs" href="/pretty/{{ obj.id }}/delete/">删除</a>
            </td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
</div>

{% endblock %}

pretty add:

{% extends 'layout.html' %}

{% block content %}

<div class="modal modal-signin position-static d-block bg-secondary py-5" tabindex="-1" role="dialog" id="modalSignin">
  <div class="modal-dialog" role="document">
    <div class="modal-content rounded-4 shadow">
      <div class="modal-header p-5 pb-4 border-bottom-0">
        <!-- <h1 class="modal-title fs-5" >Modal title</h1> -->
        <h1 class="fw-bold mb-0 fs-2">新建用户</h1>
      </div>

      <div class="modal-body p-5 pt-0">
        <form method="post">
          {% csrf_token %}
          <div class="form-floating mb-3">
            <input type="text" class="form-control rounded-3" id="floatingInput" placeholder="姓名" name="user">
            <label for="floatingInput">姓名</label>
          </div>

          <div class="form-floating mb-3">
            <input type="text" class="form-control rounded-3" id="floatingInput" placeholder="密码" name="pwd">
            <label for="floatingInput">密码</label>
          </div>

          <div class="form-floating mb-3">
            <input type="text" class="form-control rounded-3" id="floatingInput" placeholder="年龄" name="age">
            <label for="floatingInput">年龄</label>
          </div>

          <div class="form-floating mb-3">
            <input type="text" class="form-control rounded-3" id="floatingInput" placeholder="工资" name="ac">
            <label for="floatingInput">工资</label>
          </div>

          <div class="form-floating mb-3">
            <input type="text" class="form-control rounded-3" id="floatingInput" placeholder="入职时间" name="ctime">
            <label for="floatingInput">入职时间</label>
          </div>

          <div class="form-floating mb-3">
<!--            <input type="text" class="form-control rounded-3" id="floatingInput" placeholder="性别" name="title">-->
            <select name="gd" class="form-control">
              {% for item in gender_choices %}
              <option value="{{ item.0 }}">{{ item.1 }}</option>
              {% endfor %}
            </select>
          </div>

          <div class="form-floating mb-3">
<!--            <input type="text" class="form-control rounded-3" id="floatingInput" placeholder="所属部门" name="title">-->
            <select name="dp" class="form-control">
              {% for item in depart_list %}
              <option value="{{ item.id }}">{{ item.title }}</option>
              {% endfor %}
            </select>
          </div>
          <button class="w-100 mb-2 btn btn-lg rounded-3 btn-primary" type="submit">提交</button>
        </form>
      </div>
    </div>
  </div>
</div>

{% endblock %}

pretty list

{% extends 'layout.html' %}

{% block content %}


<div class="modal modal-signin position-static d-block bg-secondary py-5" tabindex="-1" role="dialog" id="modalSignin">
  <div class="modal-dialog" role="document">
    <div class="modal-content rounded-4 shadow">
      <div class="modal-header p-5 pb-4 border-bottom-0">
        <!-- <h1 class="modal-title fs-5" >Modal title</h1> -->
        <h1 class="fw-bold mb-0 fs-2">编辑靓号</h1>
      </div>

      <div class="modal-body p-5 pt-0">
        <form method="post" novalidate>
          {% csrf_token %}

            {% for field in form %}
          <div class="form-group mb-3">
            <label>{{ field.label }}</label>{{ field }}
            <span class="form-group mb-1" style="font-size:12px;color:red">{{ field.errors.0 }}</span>
          </div>

            {% endfor %}
          <button class="w-100 mb-2 btn btn-lg rounded-3 btn-primary" type="submit">提交</button>
        </form>
      </div>
    </div>
  </div>
</div>


{% endblock %}

layout

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.staticfile.net/twitter-bootstrap/5.1.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start">
        <a href="/" class="d-flex align-items-center mb-2 mb-lg-0 text-white text-decoration-none">
            <svg class="bi me-2" width="40" height="32" role="img" aria-label="Bootstrap">
                <use xlink:href="#bootstrap"></use>
            </svg>
        </a>

        <ul class="nav col-12 col-lg-auto me-lg-auto mb-2 justify-content-center mb-md-0">
            <li><a href="#" class="nav-link px-2 text-secondary">联通用户管理</a></li>
            <li><a href="/depart/list/" class="nav-link px-2 text-secondary">部门管理</a></li>
            <li><a href="/user/list/" class="nav-link px-2 text-secondary">用户管理</a></li>
            <li><a href="/pretty/list/" class="nav-link px-2 text-secondary">靓号管理</a></li>

        </ul>

        <form class="col-12 col-lg-auto mb-3 mb-lg-0 me-lg-3" role="search">
            <input type="search" class="form-control form-control-dark text-bg-dark" placeholder="Search..."
                   aria-label="Search">
        </form>

        <div class="text-end">
            <button type="button" class="btn btn-outline-dark me-2">登录</button>
            <button type="button" class="btn btn-warning">高治中</button>
        </div>
    </div>
</div>

<div>

        {% block content %}
        {% endblock %}

</div>

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script src="https://cdn.staticfile.net/twitter-bootstrap/5.1.1/js/bootstrap.min.js"></script>
</body>
</html>
posted @ 2025-07-10 09:54  crockery  阅读(12)  评论(0)    收藏  举报