[英]Django ModelForm add extra fields from the ForeignKey related fields
# models.py
class Book(Model):
title = CharField(max_length=100)
publisher = ForeignKey('Publisher')
class Publisher(Model):
name = CharField(max_length=100)
address = TextField()
# forms.py
class BookForm(ModelForm):
class Meta:
model = Book
fields = ('title', 'publisher__name', 'publisher__address',)
I am trying to breakdown the ForeignKey
fields, so that the user can input the publisher directly in the BookForm
. 我正在尝试细分ForeignKey
字段,以便用户可以在BookForm
直接输入发布BookForm
。
However 'publisher__name', 'publisher__address'
is not a valid fields. 但是'publisher__name', 'publisher__address'
不是有效的字段。
Assuming that every Book submission will create a new Publisher record. 假设每个Book提交都将创建一个新的Publisher记录。 How can I achieve this using Django Form? 如何使用Django Form实现此目的?
You can just declare both fields in your ModelForm
and save them inside ModelForm.save()
method: 您可以在ModelForm
声明两个字段,然后将它们保存在ModelForm.save()
方法中:
class BookForm(ModelForm):
# declare fields here
publisher_name = CharField()
publisher_address = TextField()
class Meta:
model = Book
fields = ('title',)
def save(self, commit=True):
book = super(BookForm, self).save(commit=False)
publisher = Publisher(name=self.cleaned_data['publisher_name'],
address=self.cleaned_data['publisher_address'])
publisher.save()
book.publisher = publisher
if commit:
book.save()
return book
Working example for you 为你工作的例子
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ('title', 'publisher')
pub_name = forms.CharField(max_length=30, required=False)
pub_addr = forms.CharField(max_length=30, required=False)
def __init__(self, *args, **kwargs):
super(BookForm, self).__init__(*args, **kwargs)
self.fields['publisher'].required = False
def clean(self):
pub_name = self.cleaned_data.get('pub_name')
pub_addr = self.cleaned_data.get('pub_addr')
pub, created = Publisher.objects.get_or_create(name=pub_name, address=pub_addr)
self.cleaned_data['publisher'] = pub
return super(BookForm, self).clean()
In views 在视图中
#data = {'title':"Dd", "pub_name":"fff", "pub_addr":"Ddddsds"}
myform = = BookForm(data)
myform.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.