[英]ModelChoiceField initial value from db
I tried to find out how to set the initial value of a ModelChoiceField, I found many answers to this question but I don't really get them. 我试图找出如何设置ModelChoiceField的初始值,我找到了这个问题的很多答案,但我并没有真正得到它们。 I understand that I can set "initial" when calling the form in admin.py but then a model instance is mentioned and I am lost. 我了解可以在admin.py中调用表单时设置“初始”,但是随后提到了模型实例,我迷路了。
This is my 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"
This is my forms.py 这是我的forms.py
class ArticleForm(forms.ModelForm):
category = forms.ModelChoiceField(queryset=Menu.objects.order_by('name').filter(category=True))
This is my admin.py 这是我的admin.py
class ArticlesAdmin(admin.ModelAdmin):
form = ArticleForm
list_display = ('headline','category', 'extract', 'image', 'added', 'updated', 'frontpage', 'active')
admin.site.register(Articles, ArticlesAdmin)
When I edit the article in the admin section I want the stored value of the category to be the initial value for the ModelChoiceField. 当我在管理部分中编辑文章时,我希望类别的存储值是ModelChoiceField的初始值。 Do you get what I mean? 你明白我的意思吗?
In admin.py there should be something like: 在admin.py中应该有类似以下内容:
form = ArticleForm(initial = {'category': instance.something})
*EDIT: I added ForeignKey as suggested *编辑:我根据建议添加了ForeignKey
category = models.ForeignKey(Menu)
and admin.py looks like this: 和admin.py看起来像这样:
class ArticlesAdmin(admin.ModelAdmin):
form = ArticleForm
list_display = ('headline','category', 'extract', 'image', 'added', 'updated', 'frontpage', 'active')
And now it's working as expected! 现在它正在按预期工作!
This code should work: 此代码应工作:
form = ArticleForm(initial = {'category': pk})
pk
is the stored value, pk = primary key pk
是存储的值,pk =主键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.