Answer the question
In order to leave comments, you need to log in
How to add categories in Django?
I recently started building my first Django site, it's almost done, but I need to add categories.
To be honest, I made the site based on a video lesson and I don’t understand how everything works.
Please explain how I can add categories to the site, so that I can add categories in the admin panel, when adding an article, I can choose which category to add it to, and display a list of categories on the site.
Explain as a child: what to write in which file, where to do migrations, in general, everything is in order with the code.
I found a couple of articles on the Internet on this topic, but they did not help.
I am making a website according to the course: [itproger] [Gosha Dudar] Full study of Python
Answer the question
In order to leave comments, you need to log in
You just need to add a Category model and link it to the Article model.
in the models.py file, where you write the article model like this
# Модель категории
class Category(models.Model):
name = models.CharField(max_length=64, verbose_name='название')
# Модель статья
class Article(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='категория')
# другие поля ....
)
from .models import Category, Article
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name']
class ArticleAdmin(admin.ModelAdmin):
list_display = ['category', ...]
admin.site.register(Category, CategoryAdmin)
admin.site.register(Article, ArticleAdmin)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question