来自db的ModelChoiceField初始值

时间:2015-11-19 13:50:14

标签: python django

我试图找出如何设置ModelChoiceField的初始值,我找到了很多这个问题的答案,但我并没有真正得到它们。我知道在admin.py中调用表单时我可以设置“初始”但是然后提到了一个模型实例而且我迷路了。

这是我的models.py

class Articles(models.Model):
    headline = models.CharField('Rubrik', max_length=200)
    category = models.CharField('Kategori', max_length=200, blank=True)
    extract = models.TextField('Utdrag')
    image = ImageField('Bild', upload_to='articles', blank=True, default="")
    text = RichTextUploadingField('Text', blank=True, default="")
    added = models.DateTimeField('Publicerad', default=timezone.now,     blank=True)
    updated = models.DateTimeField('Uppdaterad',auto_now=True)
    frontpage = models.BooleanField('Visa på startsida', default=True)
    active = models.BooleanField('Aktiv', default=False)

    def save(self, *args, **kwargs):
        if self.added is None:
            self.added = timezone.now
        super(Articles, self).save(*args, **kwargs)

    def __unicode__(self):
        return '%s' % (self.headline)

    class Meta:
        verbose_name = "artikel"
        verbose_name_plural = "Artiklar"

这是我的forms.py

class ArticleForm(forms.ModelForm):
category = forms.ModelChoiceField(queryset=Menu.objects.order_by('name').filter(category=True))

这是我的admin.py

class ArticlesAdmin(admin.ModelAdmin):
form = ArticleForm
list_display = ('headline','category', 'extract', 'image', 'added', 'updated', 'frontpage', 'active')
admin.site.register(Articles, ArticlesAdmin)

当我在admin部分编辑文章时,我希望类别的存储值是ModelChoiceField的初始值。你知道我的意思吗?

在admin.py中应该有类似的内容:

form = ArticleForm(initial = {'category':  instance.something})

*编辑:我按建议添加了ForeignKey

category = models.ForeignKey(Menu)

和admin.py看起来像这样:

class ArticlesAdmin(admin.ModelAdmin):
form = ArticleForm
list_display = ('headline','category', 'extract', 'image', 'added', 'updated', 'frontpage', 'active')

现在它按预期工作了!

1 个答案:

答案 0 :(得分:0)

此代码应该有效:

form = ArticleForm(initial = {'category':  pk})

pk是存储值,pk =主键