Reputation: 697
(first of all sorry for my bad English)
I need to know if i can limit the number of objects that a user can create in a specific model, taking the number of object admitted to create from the user profile.
I go to try to explain this. i have this model
class StoreBranchOffice(models.Model):
store = models.ForeignKey(
StoreBranchOffice,
verbose_name=_('store branch')
)
name = models.CharField(
max_length=30,
verbose_name=_('name'),
)
email = models.EmailField(
blank=True,
verbose_name=_('email'),
)
phone = models.CharField(
max_length=15,
verbose_name=_('phone'),
)
address = models.CharField(
max_length=100,
verbose_name=_('address'),
)
User Profile Model
class UserProfile(models.Model):
# Relations
user = models.OneToOneField(
User,
verbose_name=_('User'),
)
store_branch = models.ForeignKey(
Store,
verbose_name=_('Store'),
)
# Attributes - Mandatory
level = models.IntegerField(
choices=LEVEL_CHOICES,
default=1,
verbose_name=_('Level'),
)
stores_enable = models.BooleanField(
default=True,
verbose_name=_('Stores Enable'),
)
branch_max = models.IntegerField(
default=1,
verbose_name=_('branches admited')
)
Well, in the userprofile, i have a field that have the number of branch office admitted for the user... Well i need to check if the user try to create a branch office, if have admitted create branch office or if the user already have the maximum of branch offices admitted!
Thanks very much!!!
Upvotes: 0
Views: 1886
Reputation: 9245
You could do it in views like this,
def your_view(request):
if form.is_valid():
store = request.user.store_branch
max_count = request.user.branch_max
if StoreBranchOffice.objects.filter(store=store).count() >= max_count:
return #Your error message
Or you could do this in your form validation,
class StoreBranchOfficeForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
self.user = user
super(StoreBranchOfficeForm, self).__init__(*args, **kwargs)
class Meta:
model = StoreBranchOffice
fields = '__all__'
def clean(self):
store_id = self.cleaned_data.get('store')
store = Store.objects.get(id=store_id)
if not store == self.user.userprofile.store:
raise ValidationError("Not Authorised")
max_count = self.user.branch_max
if StoreBranchOffice.objects.filter(store=store).count() >= max_count:
raise ValidationError("Maximum count of offices reached.")
return super(StoreBranchOfficeForm, self).clean()
Then it will be validated when you call form.is_valid()
in your view everytime..
But you need to pass user into the form each time,
form = StoreBranchOfficeForm(user=request.user)
Upvotes: 2