Can I restrict object creation to a model in the admin panel?
If it's just an administrator that you want to influence (and don't want to influence the database model), you can create your own 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)
An alternative strategy to do the same is to create a custom ModelForm for the HomePage using a method clean
that provides the only HomePage requirement. This will cause your request to appear as a validation error rather than 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)
If this is "one home page per user" you will need a HomePage to have a ForeignKey for the user and adapt above. You may also need to store the current User object in threadlocals in order to access it fromHomePageModelForm.clean
source to share
If you want to limit Homepage
one for each user, you can use a one-to-one ratio OneToOneField
. As for the N - a pre_save
signal limitation , might be helpful.
source to share