Django ModelForm从ForeignKey相关字段添加额外字段

时间:2015-06-20 05:51:39

标签: django django-forms

# 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 中输入发布商。

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

假设每个图书提交都会创建一个新的发布者记录。 如何使用Django Form实现这一目标?

2 个答案:

答案 0 :(得分:1)

您可以在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

答案 1 :(得分:1)

适合您的工作示例

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