Hello, I’m new in django and I’m stuck on a problem.
I am working on my blog where each post consists of many blocks of various models like images/text/videos etc. I want to make a convenient post editor, where on one “edit page” you can watch your current blocks all together with its content and create new various blocks at the same time and edit/delete old ones without moving to new pages.
I have the following models:
class Post(models.Model):
title = models.CharField(max_length=500)
main_image = models.ImageField(upload_to=main_path)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post')
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
class Content(models.Model):
post = models.ForeignKey(Post,related_name='contents',on_delete=models.CASCADE)
content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE,limit_choices_to={'model__in':(
'text',
'video',
'image',
'file')})
object_id = models.PositiveIntegerField()
item = GenericForeignKey('content_type', 'object_id')
Each content instance related to model for image,text etc through GenericForeignKey.
class ItemBase(models.Model):
post = models.ForeignKey(Post,
related_name='%(class)s_related',
on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
def __str__(self):
return f'{self.__class__.__name__} from {self.post}'
class Text(ItemBase):
content = models.TextField()
class Image(ItemBase):
file = models.ImageField(upload_to=path)
I took this structure from the book I studied from, and I did not find a better solution for a post consisting of blocks.
As i undersnand, i need somehow put all related to my post content instances(and i also yet don’t understand how get access to item instance from content instance) in one form and send them in view, but I didn’t find any hint on how to build form and view that matches what I need.
I don’t even know if this is possible or not, maybe I need to completely change the structure of my database… but i will be very appreciated for any tips and help. I hope I made my problem clear