2011-04-26 62 views
0

試圖在管理頁面中將我的對象限制爲1。我得到「主鍵'u'add/foo'的newuserpath對象不存在。」如果它只是在沒有設置任何內容的情況下返回就可以了,但理想情況下會顯示一條錯誤消息。這是我在我的admin.py中。限制admin中對象的創建

 
from django.contrib import admin 
from fileman.models import Newuserpath 
from django.http import HttpResponseRedirect 

class NewuserpathAdmin(admin.ModelAdmin): 
    def add_view(self, request): 
     if request.method == "POST": 
      # Assuming you want a single, global Newuserpath object 
      if Newuserpath.objects.count() > 0: 
       # redirect to a page saying 
       # you can't create more than one 
       return HttpResponseRedirect('foo') 
     return super(NewuserpathAdmin, self).add_view(request) 

admin.site.register(Newuserpath, NewuserpathAdmin) 

我在這裏下的最佳答案:在forms.py添加代碼,並從那裏將其導入使用其他方法Is it possible to limit of object creation of a model in admin panel?

它只是不相當幹活嘗試。但我不確定如何在我的admin.py中使用它。

回答

0

錯誤只是您使用相對路徑進行重定向 - 因此瀏覽器將'foo'添加到現有網址admin/app/newuserpath/add/

管理最好的方法是使用URL反向作用 - 假設你已經給你的錯誤頁面URL配置名稱「newuserpath_error」:

return HttpResponseRedirect(reverse('newuserpath_error')) 
+0

謝謝您的回答!我戳了一下,發現一個適合的解決方案。 msg ='我的消息給用戶', self.message_user(request,msg), return HttpResponseRedirect(request.path) – leffe 2011-04-26 09:35:16