I have a Django Post model contains images, text, date of creation and owner who can add other users to view it. I want to add a feature which allows user who is in the shared_to Field to add an image only once. Therefore, I have created ManyToMany Field in order to check if user has already added his image or not. If not, allow him to add an image along with his id so that he won't be able to do that again. I've tried some things in order to add users to ManyToMany field automatically, and check if they are already in it but won't work.
model.py
class Post(models.Model):
post_name = models.CharField(max_length=255)
post_text = models.TextField(max_length=360, blank=True)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name='owner_user', on_delete=models.SET(get_deleted_user), default=1)
created_on = models.DateTimeField(default=timezone.now)
date_to_open = models.DateTimeField(blank=False)
shared_to = models.ManyToManyField(UserProfile, blank=True, related_name='shared_to_user')
image_editor = models.ManyToManyField(UserProfile, blank=True, related_name='image_editor_user')
def __str__(self):
return self.post_name
def save(self, *args, **kwargs):
super(Post, self).save(*args, **kwargs)
class PostImage(models.Model):
post_file = models.FileField(blank=True, null=True,
upload_to='media/covers/%Y/%m/%D/')
gallery_post = models.ForeignKey(Capsule, related_name='images', on_delete=models.CASCADE)
urls.py
path('addimage/<int:pk>/', views.AddImageView.as_view(), name='createimage'),