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

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

在这里插入图片描述

新建一个项目 backend

使用pycharm创建app

startapp app

项目目录

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

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

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'",
        }
    }
}

迁移数据模型

makemigrations
migrate

查看数据库表

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             |
+----------------------------+

在数据库模拟创建数据

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

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

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

<!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

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

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

<!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

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

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

<!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

#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})


在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_51882166/article/details/132276538