Can I restrict object creation to a model in the admin panel?

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

For example, I have a model named "Home" and in the admin panel I don't want the user to be able to create multiple instances of "Home".

Is there a way to do this?

+2


source to share


3 answers


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

+7


source


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.



0


source


Try

class HomePage(models.Model):
  user = models.ForeignKey(User, unique=True)
  homepage = models.CharField(max_length=100, unique=True)

  class Meta:
    unique_together = (("user", "homepage"),)

      

0


source







All Articles