How to create an inline formset for a reverse foreign key relationship

谁都会走 提交于 2019-11-29 17:29:23

You've misunderstood what an inline formset is. It's for editing the "many" side of a one-to-many relationship: that is, given a parent model of City, you could edit inline the various Properties that belong to that city.

You don't want a formset at all to simply edit the single City that a property can belong to. Instead, override the city field within your Property form to be a TextField, and either create a new City or find an existing one in the clean_city method.

class PropertyForm(forms.ModelForm):
    city = forms.TextField(required=True)

    class Meta:
        model = Property
        exclude = ('city',)

    def __init__(self, *args, **kwargs):
        super(PropertyForm, self).__init__(*args, **kwargs)
        if self.instance and not self.data:
            self.initial['city'] = self.instance.city.name

    def save(self, commit=True):
        city_name = self.cleaned_data['city']
        city, _ = City.objects.get_or_create(name=city_name)
        instance = self.save(commit=False)
        instance.city = city
        if commit = True:
            instance.save()
        return instance
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!