views:

59

answers:

3

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?

A: 

If you want to limit Homepage to one for every user, then you could use one-to-one relation, with OneToOneField. As for limiting to N - a pre_save signal might be useful.

PiotrLegnica
A: 

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"),)
Andrew Sledge
+2  A: 

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)

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)

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

spookylukey
thanks.. this is a very clear explanation;)
israkir