Django 里的表格内容做修改

当Django里表格内容需要做修改,可以这么操作。

先看效果图

修改后的表格


1. 先得在 asset_list.html 里修改。你们的html有可能跟我不一样

html 复制代码
<table border="1px">
    <thead>
        <tr>
            <th>ID</th>
            <th>标题</th>
            <th>价格</th>
            <th>分类</th>
            <th>所属部门</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        {% for obj in queryset %}
        <tr>
            <td>{{ obj.id }}</td>
            <td>{{ obj.name }}</td>
            <td>{{ obj.price }}</td>
            <td>{{ obj.get_category_display }}</td>
            <td>{{ obj.depart.title }}</td>
            <td>
            	<!-- 添加这里 -->
                <a href="/asset/edit/?aid={{ obj.id }}">编辑</a>
                <a href="#">删除</a>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>

2.urls.py 文件里添加新的url

python 复制代码
from django.contrib import admin
from django.urls import path
from apps.assetManagement import views as am_views

urlpatterns = [
    path('asset/list/', am_views.asset_list),
    path('asset/edit/', am_views.asset_edit),

]

3.views.py 文件里修改

python 复制代码
class AssetModelForm(forms.ModelForm):
    #newField = forms.CharField()
    class Meta:
        model = models.AssetSet 
        fields = ['name', 'price', 'category', 'depart']
        #fields = "__all__"

        """
        # 单一的给某个field添加样式
        widgets = {
            'category': forms.Select(attrs={'style': "width: 300px;"})
        }
        """

    # 给所有的 field 提供样式
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if name == "price":
                continue
            field.widget.attrs['style'] = "width: 100px"

def asset_edit(request):
    aid = request.GET.get('aid')
    asset_object = models.AssetSet.objects.filter(id=aid).first()
    if request.method == 'GET':
        form = AssetModelForm(instance=asset_object)  # instance的作用是显示默认值
        return render(request, 'asset_edit.html', {'form': form})
    
    form = AssetModelForm(data = request.POST, instance=asset_object)
    if form.is_valid:
        form.save()
        return redirect('/asset/list/')
    else:
        return render(request, 'asset_edit.html', {'form': form})

做了上面的三步之后,就可以实现修改了。


点个赞呗~

相关推荐
IRevers35 分钟前
【YOLO】YOLO-Master 腾讯轻量级YOLO架构超越YOLO-13(含检测和分割推理)
图像处理·人工智能·pytorch·python·yolo·transformer·边缘计算
橙露1 小时前
Python 异步爬虫进阶:协程 + 代理池高效爬取实战
开发语言·爬虫·python
一切尽在,你来2 小时前
AI 大模型应用开发前置知识:Python 泛型编程全教程
开发语言·人工智能·python·ai编程
小雨中_3 小时前
3.1 RLHF:基于人类反馈的强化学习
人工智能·python·深度学习·算法·动态规划
Maggie_ssss_supp3 小时前
Linux-python
开发语言·python
Sunhen_Qiletian4 小时前
回归与分类的本质区别
人工智能·python
星星乘坐的船4 小时前
基于Kubernetes Python SDK实现Job创建
linux·python·kubernetes
W_Meng_H4 小时前
XXL-JOB - 集成 Python 执行器实战指南
linux·python
一切尽在,你来5 小时前
AI 大模型应用开发前置知识:Python 类型注解全教程
人工智能·python·ai编程
喵手5 小时前
Python爬虫实战:地图 POI + 行政区反查(合规接口) - 商圈热力数据准备等!
爬虫·python·爬虫实战·零基础python爬虫教学·行政区反查·地图poi·商圈热力数据准备