【发布时间】:2013-05-13 03:15:58
【问题描述】:
我有一个模型,我将拥有一个实例,因此我需要覆盖 changelist_view 以绕过它(仅当我至少保存了一条记录时),然后直接跳转到 change_view。我在网上找到了 sn-p 并且效果很好,所以我编写了我的自定义 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。
有没有更优雅的方式?
谢谢 卢克
【问题讨论】:
标签: django django-forms django-admin django-views django-urls