覆盖使用ModelForm(instance = some_instance)设置的ModelForm字段值 [英] Override a ModelForm field value set using ModelForm(instance=some_instance)
问题描述
我有以下模型 -
class Book(Model):
title = CharField(max_length = 100 )
author = ForeignKey('Author')
类作者(models.Model):
name = CharField(max_length = 100)
并且有一个标准的 ModelForm
到 Book
。
在表单中,作者
是一个 ModelChoiceField
,并呈现为< select>
。我希望它是文本字段,您可以在其中输入作者姓名 - 作者名称
。
如果已经有一个具有该名称的作者,保存的模型在其外键中使用,否则创建具有该名称的作者(并在其外键中使用) - 影响 c $ c>,像这样 - 我可以添加自定义的 我试图这样做,但我似乎不能找出如何我试过在 我如何覆盖使用 Author.get_or_create(name =我发现最简单的方法是将该字段替换为一个
CharField $($)
class BookForm(ModelForm):
author = CharField )
class Meta:
model = Book
clean
逻辑,这样我就可以做到这一点,当使用 BookForm(实例)时,我不能使用预先填充的值= some_book_object)
-the CharField
设置为作者
的 pk
,而不是它的名字。
BookForm .__ init __
中覆盖的东西无效。
ModelForm
?
c
您可以通过以下方式覆盖字段内容:
= BookForm(instance = instance,initial = {'name':instance.author.name})
I have the following models—
class Book(Model):
title = CharField(max_length=100)
author = ForeignKey('Author')
class Author(models.Model):
name = CharField(max_length=100)
And have a standard ModelForm
to Book
.
In the form, author
is a ModelChoiceField
, and is rendered as a <select>
. I'd like it to be text field where you can input the author's name—Author.name
.
If there's already an author with that name, the saved model uses that in its foreign key, otherwise an author with that name is created (and used in its foreign key)—in effect, Author.get_or_create(name=posted_name_value)
.
I've found that the simplest way is to override the field as a CharField
, like so—
class BookForm(ModelForm):
author = CharField()
class Meta:
model = Book
Although with that I can add custom clean
logic that does what I want, I can't do the same with the pre-populated value when using BookForm(instance=some_book_object)
—the CharField
gets set to the Author
's pk
, not its name.
I've tried to do this but I can't seem to find out how. I've tried overriding things in BookForm.__init__
to no avail.
How can I override a fields' value set when using instance
with a ModelForm
?
You could override the field content by this:
form = BookForm(instance=instance, initial={'name': instance.author.name})
这篇关于覆盖使用ModelForm(instance = some_instance)设置的ModelForm字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!