I got simple CreateView that is using basic ModelForm and I want to add can_view
permission for current user for this specific object after it's created . As I understand it must be done after saving object. Should I use post_save
signals for this? Keep in mind I don't want to trigger this when modifying existing object.
Asked
Active
Viewed 510 times
0

Lord_JABA
- 2,545
- 7
- 31
- 58
1 Answers
0
This could be done in the model save method
class MyModel(models.Model):
def save(self):
if 'pk' not in self:
#add you permission code here
super(MyModel, self).save()
What this does is checks if your object has a primary key. If it doesn't, then this is a new object and the permissions should be created. If there is a primary key, then this object is being edited and no permissions should be added.

hellsgate
- 5,905
- 5
- 32
- 47
-
I fought about that but in model i don't have acces to request.user. So i would need to think about some workaraund to get the user that's creating the object – Lord_JABA May 20 '14 at 15:58
-
Tried that and I got `argument of type 'ModelName' is not iterable` on the line with`if 'pk' not in self:` – Lord_JABA May 21 '14 at 15:16
-
I dont know why but `if 'pk' not in self.__dict__ ` works. But as i previously wrote `ObjectNotPersisted: Object firn lastn needs to be persisted first` – Lord_JABA May 21 '14 at 15:42
-
@ Lord_JABA, checking if is there can be done in three ways. the best is if if hasattr(self, "pk"). will return true if the attribute exists. however it does not tell you if the value of this attribute is None (i.e. will return true if pk is None. The second is if self.pk: will evaluate to true if pk has a value, but this will throw an error if pk does not exist i.e. pk not yet created. Calling pk in self.__dict__ is essentially the same as option 1. – unlockme Dec 29 '16 at 21:01