首页Python

Django同一表单添加、修改数据

2020年9月9日 19:2177

项目需求:有一个列表(Table)来显示所有数据、这个页面有添加、修改、删除、搜索功能,并且使用同一个表单(Form)来实现这些功能。

数据列表

django数据列表

数据添加和编辑

注意下面两张图的URL是不同的,但使用的是同一个表单(ModelForm),实现思路是,如果参数为0那么添加数据,否则调用主键ID的数据,并显示在表单中,修改成功后返回首页。

django数据编辑图片

一、创建数据模型(Model)

# models.py

from django.contrib.auth.models import User
from django.db import models


class Forum(models.Model):
    """问答平台模型"""
    name = models.CharField('平台', max_length=64)
    url = models.URLField('链接', max_length=200)
    index = models.IntegerField('排序', default=99)

    class Meta:
        verbose_name = '平台'
        verbose_name_plural = '问答平台'

    def __str__(self):
        return self.name


class Wenda(models.Model):
    """问答数据模型"""
    STATE = [
        (0, '未回答'),
        (1, '已回答'),
        (2, '已采纳'),
        (3, '已失效'),
    ]
    title = models.CharField('标题', max_length=128)
    url = models.URLField('链接', max_length=200)
    category = models.ForeignKey(Forum, verbose_name='问答平台', on_delete=models.CASCADE, default='1')
    tiwen_user = models.CharField('提问账号', max_length=64)
    huida_user = models.CharField('回答账号', max_length=64)
    tiwen_time = models.DateField('提问时间', auto_now_add=False)
    huida_time = models.DateField('回答时间', auto_now_add=False)
    create_time = models.DateTimeField('创建时间', auto_now_add=True)
    state = models.IntegerField('状态', choices=STATE, default=0)
    user = models.ForeignKey(User, verbose_name='用户', on_delete=models.DO_NOTHING, null=True, blank=True)

    class Meta:
        verbose_name = '问答'
        verbose_name_plural = '问答推广'

    def __str__(self):
        return self.title

二、创建表单(ModelForm)

# form.py

from django.forms import ModelForm
from django.forms import widgets
from wenda.models import Wenda


class WendaForm(ModelForm):
    class Meta:
        model = Wenda
        fields = "__all__"
        exclude = ['user']
        widgets = {
            # 这里是把tiwen_time、huida_time两个字段的前端类型改成date,目的是为了快速选择日期
            'tiwen_time': widgets.DateInput(attrs={'type': 'date', 'id': 'time'}),  
            'huida_time': widgets.DateInput(attrs={'type': 'date', 'id': 'time'}),
        }

三、创建逻辑操作(View)

# views.py

from django.db.models import Q
from django.shortcuts import render, redirect
from wenda.form import WendaForm
from wenda.models import Wenda


def wenda(request):
    # 问答列表
    if request.method == 'GET':
        wenda_list = Wenda.objects.all().order_by('-create_time')
    elif request.method == 'POST':
        input_str = request.POST.get('search_text')
        wenda_list = Wenda.objects.filter(Q(title__contains=input_str) | Q(category__name__contains=input_str))
    return render(request, 'wenda/wenda.html', locals())


def wenda_add(request, wenda_id):
    # 问答添加和修改视图
    wenda_list = None
    if str(wenda_id) == '0':
        if request.method == 'POST':
            form = WendaForm(request.POST)
            if form.is_valid():
                try:
                    form.save()
                    return redirect('/wenda/')
                except:
                    message = '数据添加失败'
        else:
            form = WendaForm()
    else:
        wenda_list = Wenda.objects.get(pk=wenda_id)
        if request.method != 'POST':
            form = WendaForm(instance=wenda_list)
        else:
            try:
                form = WendaForm(instance=wenda_list, data=request.POST)
                if form.is_valid():
                    form.save()
                    return redirect('/wenda/')
            except:
                message = '数据修改失败'

    context = {
        'form': form,
        'wenda_list': wenda_list,
    }
    return render(request, 'wenda/add.html', context)


def wenda_del(request, wenda_id):
    # 问答删除
    wenda_list = Wenda.objects.get(id=wenda_id)
    if not wenda_list:
        message = '数据删除失败'
    else:
        wenda_list.delete()
        return redirect('/wenda/')

四、创建url配置

# urls.py

from django.urls import path
from wenda import views

urlpatterns = [
    path('', views.wenda, name='wenda'),  # 首页
    path('add/<int:wenda_id>', views.wenda_add, name='add'),  # 添加和编辑
    path('delete/<int:wenda_id>',views.wenda_del,name='delete'),  # 删除
]

五、前端模板

# wenda.html

<!doctype html>
<html lang="en">
<head>
    <title>问答管理</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/nav.js"></script>
    <link rel="stylesheet" type="text/css" href="/static/css/iconfont.css">
    <link rel="stylesheet" type="text/css" href="/static/css/common.css">
</head>
<body>
<main>
    {% include 'header.html' %}
    <div class="content">
        <div class="search">
            <form action="" method="POST">
                {% csrf_token %}
                <input type="text" name="search_text" placeholder="请输入关键字">
                <button type="submit">搜索</button>
            </form>
            <a href="{% url 'add' 0 %}" class="add">添加</a>
        </div>
        <table>
            <thead>
            <tr>
                <th>序号</th>
                <th>标题</th>
                <th>链接</th>
                <th>平台</th>
                <th>提问账号</th>
                <th>提问时间</th>
                <th>回答账号</th>
                <th>回答时间</th>
                <th>创建时间</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% if wenda_list %}

                {% for wenda_list in wenda_list %}
                    <tr>
                        <td>{{ forloop.counter }}</td>
                        <td>{{ wenda_list.title }}</td>
                        <td>{{ wenda_list.url }}</td>
                        <td>{{ wenda_list.category }}</td>
                        <td>{{ wenda_list.tiwen_user }}</td>
                        <td>{{ wenda_list.tiwen_time }}</td>
                        <td>{{ wenda_list.huida_user }}</td>
                        <td>{{ wenda_list.huida_time }}</td>
                        <td>{{ wenda_list.create_time }}</td>
                        {% if wenda_list.state == 3 %}
                            <td style="color:#f60c0c">{{ wenda_list.get_state_display }}</td>
                        {% else %}
                            <td style="color:#1ad014">{{ wenda_list.get_state_display }}</td>
                        {% endif %}
                        <td><a href="{% url 'add' wenda_list.id %}">编辑</a><a
                                href="{% url 'delete' wenda_list.id %}">删除</a>
                        </td>
                    </tr>
                {% endfor %}
            {% else %}
                <tr>
                    <td style="width:100%;">没有数据</td>
                </tr>
            {% endif %}
            </tbody>
        </table>
    </div>
</main>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
    <title>问答管理</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/layui.js"></script>
    <link rel="stylesheet" href="/static/css/common.css">
</head>
<body>
{% include 'header.html' %}
<main>
    <div class="change">
        {% if wenda_list %}
            <h2>问答修改</h2>
            <form action="{% url 'add' wenda_list.id %}" method="post">
                {% csrf_token %}
                {{ form.as_p }}
                <button type="submit">保存</button>
            </form>
        {% else %}
            <h2>问答添加</h2>
            <form action="{% url 'add' 0 %}" method="post">
                {% csrf_token %}
                {{ form.as_p }}
                <button type="submit">保存</button>
            </form>
        {% endif %}
    </div>
</main>
</body>
</html>