如何修改管理表单以获取类别功能的关键字

时间:2016-04-14 13:39:39

标签: python django django-models django-forms django-admin

我在4天前开始使用Django所以我只是制作一个基本的博客应用来测试一些功能,我试图在我的文章中添加一些类别,并在我的类别中添加一些关键字。

例如:

-DEV
--- Django的
--- C ++
--- Python的
-Stories
---酷
---伤心

所以这不是那么难,但现在我正在尝试修改我的管理表单,以便根据我的主要类别提出关键字,我不知道这样做很热

models.py

from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User

# Create your models here.

class Category(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class Keyword(models.Model):
    name = models.CharField(max_length=30)
    category = models.ForeignKey('Category', on_delete=models.CASCADE)

    def __str__(self):
        return self.name

class Article(models.Model):
    STATUS_CHOICES = (
        ("d", "Draft"),
        ("p", "Published"),
        ("o", "Offline"),
        #Sheduled?
    )

    title = models.CharField(max_length=100)    
    slug = models.SlugField(blank=True, editable=False)
    content = models.TextField(null=True)
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default="d")
    date_published = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de parution")
    date_modified = models.DateTimeField(auto_now_add=False, auto_now=True, verbose_name="Dernière modification")

    category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True)
    keywords = models.ManyToManyField('Keyword') #TODO: Give only tags in function of category

    author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)#, blank=True, editable=False) #TODO: Set author automaticaly when creating article
    #TODO: Add illustration on mainpage

    def __str__(self):
        return self.title

    def save(self):
        self.slug = slugify(self.title)
        super(Article, self).save()

admin.py

from django.contrib import admin
from django import forms

from blog.models import Category, Keyword, Article


class ArticleAdminForm(forms.ModelForm):
    """
        Query specific keywords in function of the main Category
    """
    class Meta:
        model = Article
        fields = ["title", "category", "keywords"]
    def __init__(self, *args, **kwargs):
        super(ArticleAdminForm, self).__init__(*args, **kwargs)
        self.fields["keywords"].queryset = Keyword.objects.filter(category=Article.objects.get(title="This is an article").category)


class ArticleAdmin(admin.ModelAdmin):
    form = ArticleAdminForm
    filter_horizontal = ("keywords", )


    ###############
    #CHANGE STATUS#
    ###############
    def set_published(self, request, queryset):
        rows_updated = queryset.update(status='p')
        if rows_updated == 1:
            message_bit = "1 story was"
        else:
            message_bit = "%s stories were" % rows_updated
        self.message_user(request, "%s successfully marked as published." % message_bit)
    def set_offline(self, request, queryset):
        rows_updated = queryset.update(status='o')
        if rows_updated == 1:
            message_bit = "1 story was"
        else:
            message_bit = "%s stories were" % rows_updated
        self.message_user(request, "%s successfully marked as offline." % message_bit)

    #################
    #DISPLAY_SETTINGS
    #################

    list_display    = ("title", "author", "status", "category", "date_published", "date_modified")
    list_filter     = ("author", "category", "keywords", )
    date_hierarchy  = ("date_published")
    ordering        = ("-date_published", )
    search_field    = ("title", "content")

    fieldsets = (
        ("Genéral",{
            "classes": ["wide"],
            "fields": ("title", "author", "category", "keywords")
        }),
        ("Article content",{
            "description": "This form takes HTML tags. Think about it!",
            "fields": ("content", )
        }),
    )
    actions = ["set_published", "set_offline"]
    set_published.short_description = "Mark selected stories as published"
    set_offline.short_description = "Mark selected stories as offline"

class KeywordAdmin(admin.ModelAdmin):

    list_display    = ("name", "category")
    list_filter     = ("category", )
    ordering        = ("category", )
    search_field    = ("category", "name")

    fieldsets = (
        ("Add a keyword", {
            "fields": ("category", "name")
        }),
    )


admin.site.register(Category)
admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Article, ArticleAdmin)

注意:

我也试过this但是如何让它发挥作用...

1 个答案:

答案 0 :(得分:0)

好的,我继续谷歌搜索其他网站上的一些信息(和其他stackoverflow主题),我终于找到了一种方法来访问表单类中的文章数据。
所以,如果有人按照我的方式落在这个上,那么

#in admin.py
self.fields["keywords"].queryset = Keyword.objects.filter(category=Article.objects.get(id=self.instance.id).category)

注意:

在第一篇文章中,我想用它的标题识别我的文章,但我意识到多年后我会有同名的文章所以现在我检查文章ID女巫是独一无二的