本文介绍了是否可以在管理面板中限制模型的对象创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想知道是否有可能在管理面板中限制模型的对象数量?

I just want to know that is it possible to limit the number of objects of a model in admin panel?

这就是说,我有一个名为首页的模型,在管理面板中,我不希望用户可以创建多个主页实例。

It is that, for example, I have a model named 'Homepage' and in the admin panel I don't want a user can create more than one instance of Homepage.

有没有办法我可以这样做?

Is there a way I can do this?

推荐答案

如果只是要影响的管理员(而不想影响数据库模型),则可以创建一个自定义的ModelAdmin子类:

If it's just the admin that you want to affect (and don't want to affect the database model), you can create a custom ModelAdmin subclass:

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

# ...

admin.site.register(HomePage, HomePageAdmin)

另一种做同样事情的策略是为HomePage创建一个自定义的ModelForm,其中一个 clean 方法强制执行单个HomePage需求。这将使您的需求显示为验证错误,而不是重定向(或数据库错误):

An alternative strategy to do the same thing is to create a custom ModelForm for HomePage, with a clean method that enforces the single HomePage requirement. This will make your requirement appear as a validation error, rather than as a redirect (or as a database error):

from django import forms
from django.forms.util import ErrorList

class HomePageModelForm(forms.ModelForm):
    def clean(self):
        if HomePage.objects.count() > 1:
            self._errors.setdefault('__all__', ErrorList()).append("You can only create one HomePage object.")
        return self.cleaned_data

# ...
class HomePageAdmin(admin.ModelAdmin):
    form = HomePageModelForm

# ...

admin.site.register(HomePage, HomePageAdmin)

如果是每个用户一个HomePage,您需要HomePage才能有一个ForeignKey用户并适应上述。您可能还需要将当前User对象存储在threadlocals中,以便从 HomePageModelForm.clean

If it's "one HomePage per user", you will need HomePage to have a ForeignKey to User and adapt the above. You may also need to store the current User object in threadlocals in order to access it from HomePageModelForm.clean

这篇关于是否可以在管理面板中限制模型的对象创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 10:57