[Answered ]-Django ModelForm add extra fields from the ForeignKey related fields

1👍

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
👤bellum

1👍

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

Leave a comment