Django框架 靓号管理(增删改查)

Django框架 靓号管理(增删改查)

新建一个项目 backend

使用pycharm创建app

python 复制代码
startapp app

项目目录

powershell 复制代码
C:\code\backend
├── app
|  ├── admin.py
|  ├── apps.py
|  ├── migrations
|  ├── models.py
|  ├── tests.py
|  ├── views.py
|  └── __init__.py
├── backend
|  ├── asgi.py
|  ├── settings.py
|  ├── urls.py
|  ├── wsgi.py
|  └── __init__.py
├── manage.py
├── templates
└── venv
   ├── Lib
   ├── pyvenv.cfg
   └── Scripts

创建模型

app/models.py

python 复制代码
from django.db import models


# Create your models here.
class PrettyNum(models.Model):
    mobile = models.CharField(verbose_name='手机号', max_length=11)
    # 想要循序为空 null = True blank =Tree
    price = models.IntegerField(verbose_name='价格', default=0)

    level_choices = (
        (1, "1级"),
        (2, '2级'),
        (3, '3级'),
    )
    level = models.SmallIntegerField(verbose_name='级别', choices=level_choices, default=1)
    status_choices = (
        (1, "已占用"),
        (2, "未使用")
    )
    status = models.SmallIntegerField(verbose_name="状态", choices=status_choices, default=2)

数据库配置并注册app

backend/settings.py

python 复制代码
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #注册app
    'app.apps.AppConfig'
]

#这里使用mysql数据库
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'tmpdb', #这里填写数据名称
        'USER': 'root',
        'PASSWORD': '自定义数据库密码',
        'HOST': 'mysql所在服务器IP',
        'PORT':'mysql服务端口',
        'OPTIONS':{
            "init_command":"SET sql_mode='STRICT_TRANS_TABLES'",
        }
    }
}

迁移数据模型

python 复制代码
makemigrations
migrate

查看数据库表

sql 复制代码
mysql> show tables;
+----------------------------+
| Tables_in_tmpdb            |
+----------------------------+
| app_prettynum              |
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+

在数据库模拟创建数据

sql 复制代码
mysql> SELECT * FROM app_prettynum ;
+----+------------+-------+-------+--------+
| id | mobile     | price | level | status |
+----+------------+-------+-------+--------+
|  1 | 123456     |    19 |     1 |      1 |
|  2 | 123457686  |    17 |     1 |      1 |
|  3 | 1234576888 |    10 |     1 |      1 |
|  4 | 1234576888 |    10 |     1 |      1 |
|  5 | 1234576888 |    10 |     1 |      1 |
|  6 | 1234576888 |    10 |     1 |      1 |
|  7 | 1234576888 |    10 |     1 |      1 |
+----+------------+-------+-------+--------+

靓号列表

  • url
  • 函数
    • 获取所有靓号
    • 通过html+render将靓号罗列出

backend/urls.py

python 复制代码
from django.contrib import admin
from django.urls import path
from app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    # 列表
    path('pretty/list/', views.pretty_list),
]

app/views.py

python 复制代码
from django.shortcuts import render

from app.models import *


# Create your views here.
def pretty_list(req):
    """靓号列表"""
    # 选择倒叙排序
    queryset = PrettyNum.objects.all().order_by("-price")

    return render(req, 'pretty_list.html', {"queryset": queryset})

在app下创建templates目录

app/templates/pretty_list.html

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>靓号列表</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="panel panel-default">
    <!-- Default panel contents -->
    <div class="panel-heading">Panel heading</div>
    <div class="panel-body">

    </div>

    <!-- Table -->
    <table class="table">
        <thead>
        <tr>
            <th>ID</th>
            <th>号码</th>
            <th>价格</th>
            <th>级别</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        {% for obj in queryset %}
            <tr>
                <th>{{ obj.id }}</th>
                <th>{{ obj.mobile }}</th>
                <th>{{ obj.price }}</th>
                <th>{{ obj.get_level_display }}</th>
                <th>{{ obj.get_status_display }}</th>

            </tr>

        {% endfor %}

        </tbody>

    </table>
</div>

</body>
</html>

启动服务,访问

准备提交添加

backend/urls.py

python 复制代码
from django.contrib import admin
from django.urls import path
from app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    # 列表
    path('pretty/list/', views.pretty_list),
    # 添加
    path('pretty/add/', views.pretty_add),
]

app/views.py

python 复制代码
from django.core.validators import RegexValidator
from django.shortcuts import render, redirect
from django import forms
from app.models import *


# Create your views here.
def pretty_list(req):
    """靓号列表"""
    # 选择倒叙排序
    queryset = PrettyNum.objects.all().order_by("-price")

    return render(req, 'pretty_list.html', {"queryset": queryset})


class PrettyModelForm(forms.ModelForm):
    class Meta:
        model = PrettyNum
        fields = ['mobile', 'price', 'level', 'status']


def pretty_add(request):
    """添加"""
    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/')

    return render(request, 'pretty_add.html', {"form": form})

app/templates/pretty_add.html

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>添加</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div style="padding: 100px 100px 10px;">
    <form method="post" novalidate>
        {% csrf_token %}
        {% for filed in form %}
            <div>
                <label>{{ filed.label }}</label>
                {{ filed }}

            </div>




        {% endfor %}
        <button type="submit" class="button">提交</button>


    </form>
</div>

</body>
</html>

编辑靓号

  • 列表页面:/pretty/数字/edit/
  • url
  • 函数
    • 根据ID获取当前编辑对象
    • ModelForm配合,默认显示数据
    • 提交修改

backend/urls.py

python 复制代码
from django.contrib import admin
from django.urls import path
from app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    # 列表
    path('pretty/list/', views.pretty_list),
    # 添加
    path('pretty/add/', views.pretty_add),
    # 编辑
    path('pretty/<int:nid>/edit/', views.pretty_edit),
]

app/views.py

python 复制代码
from django.core.validators import RegexValidator
from django.shortcuts import render, redirect
from django import forms
from app.models import *





class PrettyEditModelForm(forms.ModelForm):
    mobile = forms.CharField(disabled=True, label="手机号")  # 不允许修改

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





def pretty_edit(request, nid):
    row_obj = PrettyNum.objects.filter(id=nid).first()
    if request.method == "GET":
        form = PrettyEditModelForm(instance=row_obj)
        return render(request, 'pretty_edit.html', {"form": form})

    form = PrettyEditModelForm(data=request.POST, instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')

    return render(request, 'pretty_edit.html', {"form": form})

app/templates/pretty_edit.html

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>添加</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div style="padding: 100px 100px 10px;">
    <form method="post" novalidate>
        {% csrf_token %}
        {% for filed in form %}
            <div>
                <label>{{ filed.label }}</label>
                {{ filed }}

            </div>




        {% endfor %}
        <button type="submit" class="button">提交</button>


    </form>
</div>

</body>
</html>

查询

根据电话号码查询

app/views.py

python 复制代码
#Get方法
def pretty_list(request):
    """靓号列表"""
    # 选择倒叙排序
    data_dict = {}
    val = request.GET.get('q')
    queryset = queryset = PrettyNum.objects.all().filter(**data_dict).order_by("-price")

    if val:
        data_dict["mobile__contains"] = val
        queryset = PrettyNum.objects.all().filter(**data_dict).order_by("-price")

    return render(request, 'pretty_list.html', {"queryset": queryset})
相关推荐
斯特凡今天也很帅5 分钟前
clickhouse常用语句汇总——持续更新中
数据库·sql·clickhouse
超级小忍1 小时前
如何配置 MySQL 允许远程连接
数据库·mysql·adb
吹牛不交税2 小时前
sqlsugar WhereIF条件的大于等于和等于查出来的坑
数据库·mysql
hshpy2 小时前
setting up Activiti BPMN Workflow Engine with Spring Boot
数据库·spring boot·后端
文牧之3 小时前
Oracle 审计参数:AUDIT_TRAIL 和 AUDIT_SYS_OPERATIONS
运维·数据库·oracle
篱笆院的狗3 小时前
如何使用 Redis 快速实现布隆过滤器?
数据库·redis·缓存
洛神灬殇4 小时前
【LLM大模型技术专题】「入门到精通系列教程」基于ai-openai-spring-boot-starter集成开发实战指南
网络·数据库·微服务·云原生·架构
小鸡脚来咯4 小时前
redis分片集群架构
数据库·redis·架构
christine-rr5 小时前
征文投稿:如何写一份实用的技术文档?——以软件配置为例
运维·前端·网络·数据库·软件构建
海尔辛5 小时前
SQL 基础入门
数据库·sql