Answer the question
In order to leave comments, you need to log in
How to correctly form a model for an article (post)?
We have an article about programming, the article has a title (that is, its main topic), a section to which this article belongs (category), inside the article there is text (sections) with examples in the form of images and code.
Question: How to correctly form models for such an article, so that, among other things, you can still work with information in the template .
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=400, verbose_name='Раздел')
class Article(models.Model):
title = models.CharField(max_length=400, verbose_name='Тема статьи')
category = models.ForeignKey(Category, on_delete=models.PROTECT)
class Section(models.Model):
title = models.CharField(max_length=255, verbose_name='Заголовок раздела')
text = models.TextField(blank=True, verbose_name='Текст раздела')
article = models.ForeignKey(Article, on_delete=models.CASCADE)
class Photo(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
photo = models.ImageField(upload_to=f"photos/{article.name}", verbose_name='Фотография')
class Code(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
code = models.TextField(blank=True, verbose_name='Код')
Answer the question
In order to leave comments, you need to log in
Well, at least the FK to the article in the code and photos is superfluous.
PS When uploading files, it's better to generate random names for them
import uuid
import os
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = f'{uuid.uuid4()}.{ext}'
return os.path.join('folder_path', filename) # folder_path - нужная папка (article, по идее можно вытянуть из instance)
...
...upload_to=get_file_path
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question