2015-06-20 60 views
1
# 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',) 

我試圖擊穿ForeignKey字段添加額外的字段,使用戶可以直接在BookForm輸入的出版商。的Django的ModelForm從ForeignKey的相關領域

'publisher__name', 'publisher__address'不是有效的字段。

假設每個書提交將創建一個新的發佈者記錄。 我怎樣才能實現這個使用Django窗體?

回答

0

您可以直接在你的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 
0

工作比如你

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() 

在意見

#data = {'title':"Dd", "pub_name":"fff", "pub_addr":"Ddddsds"} 
myform = = BookForm(data) 
myform.save()