标签:als field efi lte ken cts following site splay
删除页面展示:
1、路由配置:
url(r'^(\w+)/(\w+)/(\d+)/delete$', views.delete_obj, name='delete_obj'),
2、视图函数:
def delete_obj(request, app_name, model_name, id):
"""根据id删除对象"""
admin_class = site.enable_admins[app_name][model_name]
model_class = admin_class.model
model_name=model_class._meta.model_name
obj = model_class.objects.filter(id=int(id)).first()
if request.method=='POST':
obj.delete()
return redirect('/kingadmin/%s/%s' % (app_name, model_class._meta.model_name))
return render(request,'kingadmin/del_obj.html',locals())
3、前端页面:
<div class="text">
<h2>Are you sure?</h2>
<p>Are you sure you want to delete the {{ model_name }} "{{ obj }}"?
All of the following related items will be deleted:</p>
</div>
<div>
<!--展示与要删除的关联字段相关联的表记录对象-->
{% display_all_related_objs obj %}
</div>
<form method="post">
<input type="submit" value="确定删除" class="btn btn-danger">
<a href="{% url 'change_obj' app_name model_name obj.id %}">
<input type="button" value="返回" class="btn btn-info">
</a>
{% csrf_token %}
</form>
4、自定义标签手动生成相关联表记录对象:
@register.simple_tag
def display_all_related_objs(obj):
"""显示要被删除对象的所有关联对象"""
ele = "<ul>"
# 1、取出与当前对象有 外键 关联的所有 model表的关联对象,
# 例如:<class 'django.db.models.fields.reverse_related.ManyToOneRel'>
for reversed_fk_obj in obj._meta.related_objects:
# 2、拼接查询关键字,例如modelname__set
related_table_name = reversed_fk_obj.name
related_lookup_key = "%s_set" % related_table_name
# 3、子结构开始
ele += "<li>%s<ul> " % related_table_name
# 4、判断关联表对象的类型:ManyToManyField、OneToOneField、ForeignKey
if reversed_fk_obj.get_internal_type() == "ManyToManyField": # 不需要深入查找
related_objs = getattr(obj, related_lookup_key).all() # 反向查所有关联的数据
for i in related_objs:
ele += "<li><a href='/kingadmin/%s/%s/%s/change'>%s</a> 记录里与[%s]相关的的数据将被删除</li>" % (i._meta.app_label, i._meta.model_name, i.id, i, obj)
elif reversed_fk_obj.get_internal_type() == "OneToOneField": # 不需要深入查找
related_obj = getattr(obj, related_table_name, '') # 反向查所有关联的数据
if related_obj:
ele += "<li><a href='/kingadmin/%s/%s/%s/change'>%s</a> 记录里与[%s]相关的的数据将被删除</li>" % (related_obj._meta.app_label, related_obj._meta.model_name, related_obj.id, related_obj, obj)
elif reversed_fk_obj.get_internal_type() == "ForeignKey":
# 例如通过删除客户,那么就会删除 与此客户相关的客户跟踪记录 和 student_enroll信息
related_objs = getattr(obj, related_lookup_key).all() # 反向查所有关联的数据
for i in related_objs:
ele += "<li><a href='/kingadmin/%s/%s/%s/change'>%s</a></li>" % (i._meta.app_label,
i._meta.model_name,
i.id, i)
ele += display_all_related_objs(i)
ele += "</ul></li>"
ele += "</ul>"
return mark_safe(ele)
5、删除按钮 和 返回按钮:确定删除
<form method="post">
<input type="submit" value="确定删除" class="btn btn-danger">
<a href="{% url 'change_obj' app_name model_name obj.id %}">
<input type="button" value="返回" class="btn btn-info">
</a>
{% csrf_token %}
</form>
标签:als field efi lte ken cts following site splay
原文地址:https://www.cnblogs.com/fqh202/p/9461705.html