我有一个模型,我将有一个单一的实例,所以我需要覆盖changelist_view旁路它(只有当我有至少一个记录保存),并直接跳转到change_view。我发现片断在网上和它的作品,以及为它,所以我写了我的自定义changelist_view:django管理 - 覆盖changelist_view单入口模型
def changelist_view(self, request, extra_context=None):
queryset = self.model.objects.all()
if queryset.count()>0:
try:
obj = queryset[0]
return self.change_view(request, str(obj.id), extra_context)
except IndexError:
pass
return super(MyModelAdmin, self).changelist_view(request, extra_context)
这工作,直到我试图挽救。与正常的change_view不同之处在于url。正常的具有对象ID:
http://127.0.0.1:8000/admin/myapp/mymodel/2
,而不是用修改后的版本我有:
http://127.0.0.1:8000/admin/myapp/mymodel/
,如果我试图挽救我得到这个错误:
You called this URL via POST, but the URL doesn't end
in a slash and you have APPEND_SLASH set. Django can't redirect to
the slash URL while maintaining POST data. Change your form to
point to 127.0.0.1:8000/admin/myapp1/mymodel/None/ (note
the trailing slash), or set APPEND_SLASH=False in your
Django settings.
在唯一的那一刻这个技巧适用于我,它是一个HttpResponseRedirect(url),其中url为对象id硬编码的change_view url。
有没有更优雅的方式?
感谢 卢克