# 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
.
However 'publisher__name', 'publisher__address'
is not a valid fields.
Assuming that every Book submission will create a new Publisher record. How can I achieve this using Django Form?
You can just declare both fields in your ModelForm
and save them inside ModelForm.save()
method:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.