Modelform预填充外键

时间:2014-01-04 14:42:01

标签: django django-forms

尝试设置每个modelform实例的外键我有以下模型:

#models.py
Column(models.Model):
     name = models.CharField()

Input(models.Model):
    column = ForeignKey(Column)
    text = models.CharField()

forms.py中,如何为Modelform实例设置ForeignKey

#forms.py
class InputForm(forms.ModelForm):

    def __init__(self, column_parameter):
        super(InputForm, self).__init__()
        self.fields['column'].value = calc_column(column_parameter) #this of course does not set the value


    class Meta():
        model = Input

1 个答案:

答案 0 :(得分:1)

您可能不应该在init方法中设置它。如果必须这样做,请在save()方法中设置它。

def save(self, force_insert=False, force_update=False, commit=True):
    m = super(InputForm, self).save(commit=False)
    m.column = calc_column(column_parameter)
    if commit:
        m.save()
    return m

但是如果您必须设置此值,那么我建议您使用初始数据:

InputForm(initial = {'column':calc_column(column_parameter)})