Home > Mobile >  I want to set a limit for the rows only upto 5 rows which will get added from the django.models admi
I want to set a limit for the rows only upto 5 rows which will get added from the django.models admi

Time:06-28

I have a table in my models file and I want to design it such that there is a limit to only 5 rows in the table. When the limit is exceeded error has to show and input should not take.I am new to Django so if anyone had a suggestion on how to do this, it would be greatly appreciated!

CodePudding user response:

You could set a restriction on that particular model by overriding the has_add_permission() in the admin.py file. For example:

admin.py file:

# Let's say you have a model called Post
from django.contrib import admin
from .models import Post

MAX_OBJECTS = 5

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
     list_display = ['field 1', 'field 2', 'etc.']
     # other class attributes can be set here as well.

     # To allow the user to be able to add only 5 objects/rows for this model (The Post Model).
     def has_add_permission(self, request):
          if self.model.objects.count() >= MAX_OBJECTS:
               return False
          return super().has_add_permission(request)

That's an approach you could take, but there won't be any error messages though. If there are five existing rows then the add button will not be visible on the Django admin site.

You can also learn more about customizing the Django admin site in the docs.

  • Related