A
A
AlsielXD2019-09-23 18:00:36
Django
AlsielXD, 2019-09-23 18:00:36

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

1 answer(s)
L
Lyokha, 2019-10-10
@EdFonse

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='категория')
    # другие поля ....
)

It remains only to add admin.py
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)

That's all. I advise you to look at more tutorials and read the documentation (there is also in Russian), well, and various other articles.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question