首页 文章

限制在admin中创建对象

提问于
浏览
0

尝试在管理页面中将对象限制为1 . 我得到“newuserpath对象与主键u'add / foo”不存在 . 如果没有设置任何东西就会返回它,但理想情况下会出现错误消息 . 这是我在admin.py中的内容 .

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)

我在这里遵循最佳答案:Is it possible to limit of object creation of a model in admin panel?

它只是不太有用 . 我尝试使用另一种方法,在forms.py中添加代码并从那里导入 . 但我不确定如何在我的admin.py中使用它 .

1 回答

  • 0

    错误只是您使用重定向的相对路径 - 因此浏览器将 'foo' 添加到现有URL, admin/app/newuserpath/add/ .

    管理此问题的最佳方法是使用URL反向函数 - 假设您已将错误页面URLconf命名为“newuserpath_error”:

    return HttpResponseRedirect(reverse('newuserpath_error'))
    

相关问题