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

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


点个赞呗~

相关推荐
the局外人30 分钟前
FastAPI中jwt的基本使用与实践
后端·python·fastapi
mklpo14744 分钟前
为不支持sse4.2命令集的老旧设备制作Win11 26H2系统镜像,2026-10-11。
运维·windows·python
GoldenSpider.AI1 小时前
用 AI 改流程之前先做「四桶」体检:9 次返工里 8 次靠规则就能消掉(附 Python 发布前校验器)
人工智能·python·自动化·ai智能体
小白快快跑哦1 小时前
python-字符串全解(六):正则表达式-修饰符
python·正则表达式·修饰符
niucloud-admin1 小时前
JAVA V6 多商户商城 开发文档——项目启动
java·开发语言·python
CCIE-Yasuo1 小时前
个人电脑搭建AI-Qwen3-8B-学习记录
人工智能·python·学习
小猴子爱上树2 小时前
跨马翻译:批量图片翻译+视频字幕+智能抠图,跨境电商翻译工具
python·音视频
棉猴2 小时前
玩游戏学Python2-IDLE与pgzero入门
开发语言·python·游戏·玩游戏·pgzero·pgzrun
TechEdu2026062 小时前
[人工智能]Python12: SciPy 实战指南
人工智能·python·scipy
jack186893 小时前
Github Copilot 高效开发实战场景指南
python