Reputation: 2320
Now I have models.py like this
class FileCategory(models.Model):
file_type = models.CharField(_('type'), max_length=128)
def __unicode__(self):
return self.file_type
class Doc(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
file_category = models.ForeignKey('FileCategory', null=True)
file = models.FileField(upload_to='documents/',
null=True, blank=True)
class Meta:
permissions = (("upload_file", "upload file"),
("delete_file", "delete file"),
("download_file", "download file"),
("access_file", "access file"),
)
Now I want to add permissions for every FileCategory
table
For example If I have filecategory numm, dumm and summ
I want to automatically have permissions ("access_file_numm","access_file_summ","access_file_dumm", )
I tried to make a solution like this:
permissions = (bla,bla,bla,
)+\
("access_file_%s" (type.__str__() for type in FileCategory.objects.all()),
"access %s"(type.__str__() for type in FileCategory.objects.all()))
And sure I want to migrate them to the database
as Moemn answers with an edit:
def save(self, *args, **kwargs):
super(FileCategory, self).save(*args, **kwargs)
Permission.objects.get_or_create(content_type=ContentType.objects.get_for_model(Doc),
codename="access_type_%s" % self.file_type,
name="access type %s" % self.file_type)
Upvotes: 1
Views: 118
Reputation: 706
You can do this by creating Permission
dynamically after every FileCategory
creation.
e.g.
def save(self, *args, **kwargs):
super(FileCategory, self).save(*args, **kwargs)
Permission.objects.create(content_type=ContentType.get_for_model(Doc), name="access_file_%s" % self.file_type)
Permission.objects.create(content_type=ContentType.get_for_model(Doc), name="access_%s" % self.file_type)
Or you can use signals, the same idea.
Upvotes: 1