当Django里表格内容需要做修改,可以这么操作。
先看效果图
修改后的表格
1. 先得在 asset_list.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
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 文件里修改
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})
做了上面的三步之后,就可以实现修改了。
点个赞呗~
标签:__,obj,表格,form,views,request,Django,修改,asset From: https://blog.csdn.net/BSCHN123/article/details/139533972