I am creating a pluggable attachments app. Just like in Django Part 1 Tags app is created that can be assigned to any post. Think like there is a post and in that there is an option to attach an attachment and user can add as many attachment as he wants in that post. User can attach anything like pdf or image. How can I achieve this?
I have achieved this by doing something like this
#... class Attachment(models.Model): label = models.CharField(max_length=255, unique=True) attach_file = models.FileField(upload_to='attachment') def __str__(self): return self.label class AttachmentItem(models.Model): attachment = models.ForeignKey(Attachment, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) objectId = models.PositiveIntegerField() content_object = GenericForeignKey()
Adding this code in models.py of Attachment and then editing some existing files in the main app to properly deal with media files
#... MEDIA_ROOT = '/assets/media/' MEDIA_URL = '/media/' #...
Adding the above mentioned code in settings.py and the below mentioned code in main urls.py of main project
#... from django.conf.urls.static import static from django.conf import settings #... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #...
This is what I have created but I am open for any other ideas.
Now I am thinking it would be better if I delete the Attachment class and change the models.py in Attachment app to
class AttachmentItem(models.Model): short_description = models.CharField(max_length=255) attach_file = models.FileField(upload_to='attachment') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) objectId = models.PositiveIntegerField() content_object = GenericForeignKey() def __str__(self): return self.attach_file
As I don’t want to create a many to many relationship. Instead I want a one to many relationship i.e 1 post can have many attachments and not the vice versa.