我有一个模型,我将拥有一个实例,因此我需要覆盖 changelist_view 以绕过它(仅当我至少保存了一条记录时),然后直接跳转到 change_view。我在网上找到了片段,它很适合它,所以我写了我的自定义 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),将 change_view url 与对象 ID 硬编码为 url。
有没有更优雅的方式?
谢谢卢克