G
G
Grigory Dikiy2016-01-24 15:03:46
Django
Grigory Dikiy, 2016-01-24 15:03:46

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)

admin:
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)

How can I make it possible to select a category from the dropdown list? I will be very grateful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2016-01-24
@frilix

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']

In principle, fields should be used in rare cases, by default it includes all model fields.
To prevent the user from editing fields, it is better to use
https://docs.djangoproject.com/en/1.9/ref/models/f...
likes = models.PositiveIntegerField(default=0, editable=False)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question