Limit number of model instances to be created - django

前端 未结 6 1533
萌比男神i
萌比男神i 2020-12-02 20:36

I have model from which I only want to create one instance, and no more instances should be allowed.

Is this possible? I\'ve got a feeling that I\'ve seen this done

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 21:22

    If you just want to prevent users using the administrative interface from creating extra model objects you could modify the "has_add_permission" method of the model's ModelAdmin class:

    # admin.py
    from django.contrib import admin
    from example.models import Example
    
    class ExampleAdmin(admin.ModelAdmin):
      def has_add_permission(self, request):
        num_objects = self.model.objects.count()
        if num_objects >= 1:
          return False
        else:
          return True
    
    admin.site.register(Example, ExampleAdmin)
    

    This will remove the "add" button in the administrative interface preventing users from even attempting to create more than the specified number (in this case 1). Of course programatic additions will still be possible.

提交回复
热议问题