我想要一个功能,就像使用 list_editable 的 admin 一样,所以我选择了它,并且几乎从options.py
django 源代码中复制了代码。我为我的对象检索了管理员,然后保存了原始值(函数fix_old_job_admin
将它们设置回来)
这段代码解决了我的问题
job_admin = admin.site._registry[Job]
# save old values so that you can go back to them later
old_list_display = job_admin.list_display
old_list_filter = job_admin.list_filter
old_ordering = job_admin.model._meta.ordering
job_admin.list_editable = ("time", "what", "approved")
cl = ChangeList(request, job_admin.model, job_admin.list_display, job_admin.list_display_links, job_admin.list_filter, job_admin.date_hierarchy, job_admin.search_fields, job_admin.list_select_related, job_admin.list_per_page, job_admin.list_editable,job_admin.admin_site, job_admin)
# options.py from django framework lines 1181-1208 (v. 1.4)
if request.POST:
FormSet = job_admin.get_changelist_formset(request)
formset =FormSet(request.POST, request.FILES, queryset=cl.result_list)
if formset.is_valid():
changecount = 0
for form in formset.forms:
if form.has_changed():
obj = job_admin.save_form(request, form, change=True)
job_admin.save_model(request, obj, form, change=True)
job_admin.save_related(request, form, formsets=[], change=True)
change_msg = job_admin.construct_change_message(request, form, None)
job_admin.log_change(request, obj, change_msg)
changecount += 1
if changecount:
if changecount == 1:
name = force_unicode(job_admin.model._meta.verbose_name)
else:
name = force_unicode(job_admin.model._meta.verbose_name_plural)
msg = ungettext("%(count)s %(name)s was changed successfully.",
"%(count)s %(name)s were changed successfully.",
changecount) % {'count': changecount,
'name': name,
'obj': force_unicode(obj)}
job_admin.message_user(request, msg)
# call function that sets admin with original values
fix_old_job_admin(job_admin, old_list_display, old_ordering, old_list_filter)
return HttpResponseRedirect(request.get_full_path())
FormSet = job_admin.get_changelist_formset(request)
cl.formset = FormSet(queryset=cl.result_list)
context = Context({
'app_label': ContentType.objects.get_for_model(Lawyer).app_label,
'verbose_name_plural': Job._meta.verbose_name_plural.title(),
"cl": cl,
'request': request,
})
# call function that sets admin with original values
fix_old_job_admin(job_admin, old_list_display, old_ordering, old_list_filter)
return render_to_response('yourtemplate/similar_to_changelist.html', context, RequestContext(request))