Reputation: 209
I have a little problem. I want to set the limit for users in my app. For example: The new user after register and login to his account can add only one record. After added if this same user want to add next record, the app will return the alert "You are permited to add only one record". How to solve it?
Upvotes: 0
Views: 1529
Reputation: 201
You can build a model similar to this that defines the limit per user and validating the inserted data using a classmethod
:
class LimitedRecord(models.Model):
limits = 5
user = models.ForeignKey(User)
data = models.CharField(max_length=128)
@classmethod
def add_record(cls, user, data):
if not cls.can_add(user):
raise Exception('Not Allowed')
instance = cls.objects.create(user=user, data=data)
return instance
@classmethod
def can_add(cls, user):
return cls.objects.filter(user=user).count() <= cls.limits:
I separated the login here into two methods, but sure you can combine them in the same unit that adds the record.
Upvotes: 1
Reputation: 6223
Add two fields to your User
model:
class User(models.Model):
n_records_permitted = models.PositiveIntegerField(default=1)
n_records_added = models.PositiveIntegerField(default=0)
Now either don't display the relevant form(s) for Users that have user.n_records_added >= user.n_records_permitted
or include this check in the form's validation.
And of increase both counters as appropriate.
Upvotes: 0
Reputation: 1213
You need to have a way to remember if the user used their limit or not. I know 2 options here:
This is the best tutorial I have found so far regarding extending user model with some additional data: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html
No matter which solution works better for you, you'll need to check the conditions in the creation view and throw an error if the limit would be exceeded (e.g. PermissionDenied
)
Upvotes: 2