如何在django模板中创建一个modelform可编辑的外键字段?

时间:2013-11-07 17:34:38

标签: python django django-models django-forms django-templates

我有一个公司模特:

class Company(models.Model):
    companyId = models.IntegerField(unique=True, blank = True, null = True )
    address = models.ForeignKey(Address, blank = True, null = True )
    ...

和地址模型:

class Address(models.Model):
    address1 = models.CharField (max_length=300, blank = True, null = True)
    ...

我需要为外键创建一个可编辑的表单,这是我的代码:

class CompanyForm(forms.ModelForm):
    address = forms.CharField(label='Address', max_length=500, required=False)
    ...

该表单的视图是

<div class="control-group">
    <label class="control-label" for="id_address">{{ form.address.label }}</label>
   <div class="controls">
            {{ form.instance.address.address1 }}
  </div>
</div>

显示地址和标签但我无法修改该字段。 实际使该字段可编辑的方法是什么? 任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

要将字符串字段中的数据保存到fk,您需要覆盖表单保存方法。您可以在__init__方法中将初始状态设置为字符串地址字段:

class CompanyForm(forms.ModelForm):
    s_address = forms.CharField(label='Address', max_length=500, required=False)

    def __init__(self, *args, **kwargs):
        super(CompanyForm, self).__init__(*args, **kwargs)
        self.fields['s_address'].initial = self.instance.address.address1

    def save(self, commit=True):
        model = super(CompanyForm, self).save(commit=False)
        saddr = self.cleaned_data['s_address']
        if saddr:
            if model.address:
                model.address.address1 = saddr
                model.address.save()
            else:
                model.address = Address.objects.create(address1=saddr)
                # or you can try to look for appropriate address in Address table first
                # try:
                #     model.address = Address.objects.get(address1=saddr)
                # except Address.DoesNotExist:
                #     model.address = Address.objects.create(address1=saddr)

        if commit:
            model.save()

        return model

    class Meta:
        exclude = ('address',) # exclude form own address field

模板:

<div class="control-group">
    {{ form.s_address }}
</div>