Answer the question
In order to leave comments, you need to log in
Django: category binding?
Good day! Recently I started to deal with Django, and with Python in general. Decided to go through practice. I made a blog on video tutorials, but after I wanted to supplement the blog with categories, I managed to link the category to the article, and this is not what I need:
Models:
class Category(models.Model):
class Meta:
db_table = 'category'
category_title = models.CharField(max_length=100, db_index=True)
category_slug = models.SlugField(max_length=100, db_index=True)
class Article(models.Model):
class Meta:
db_table = 'article'
article_title = models.CharField(max_length=200)
article_text = models.TextField()
article_date = models.DateTimeField()
article_likes = models.IntegerField(default=0)
article_category = models.ForeignKey(Category)
class ArticleInline(admin.StackedInline):
model = Comments
extra = 1
class ArticleToCategory(admin.StackedInline):
model = Article
extra = 1
class ArticleAdmin(admin.ModelAdmin):
fields = ['article_title', 'article_text', 'article_date']
inlines = [ArticleInline]
list_filter = ['article_date']
class ArticleCategory(admin.ModelAdmin):
inlines = [ArticleToCategory]
admin.site.register(Article, ArticleAdmin)
admin.site.register(Category, ArticleCategory)
Answer the question
In order to leave comments, you need to log in
do not use db_table =
- this is for pulling django on an existing database, the structure of which cannot be changed
Naming model fields
class Article(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
created = models.DateTimeField()
likes = models.IntegerField(default=0)
category = models.ForeignKey(Category)
def __str__(self): return self.title
class ArticleAdmin(admin.ModelAdmin):
fields = ['category', 'title', 'text', 'created']
likes = models.PositiveIntegerField(default=0, editable=False)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question