限制管理中对象的创建

发布于 2024-11-03 12:13:49 字数 981 浏览 4 评论 0原文

尝试将管理页面中的对象限制为 1。我得到“主键 u'add/foo' 的 newuserpath 对象不存在。”如果它不设置任何内容就返回,但最好带有错误消息,那就可以了。这就是我的 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)

我在这里遵循最佳答案: 是否可以在管理面板中限制模型的对象创建?

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

Trying to limit my objects to 1 in admin pages. I get "newuserpath object with primary key u'add/foo' does not exist." It would be ok if it would just return without setting anything, but ideally with an error message. This is what I have in my 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)

I'm following the best answer here: Is it possible to limit of object creation of a model in admin panel?

It just doesn't quite work.I tried using the other method by adding code in forms.py and importing it from there. But I'm unsure of how to use that in my admin.py.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

避讳 2024-11-10 12:13:49

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

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

return HttpResponseRedirect(reverse('newuserpath_error'))

The error is simply that you are using a relative path for your redirect - so the browser is adding 'foo' to the existing URL, admin/app/newuserpath/add/.

The best way to manage this is to use the URL reverse function - assuming you have given your error page URLconf the name 'newuserpath_error':

return HttpResponseRedirect(reverse('newuserpath_error'))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文