在 Django 中,应该有两种方法来设置外键的初始值。我的第二种方法似乎对我不起作用,我不明白为什么:
模型:
class Task(models.Model):
contact = models.ForeignKey(Contact, null=True, blank=True)
作品:
看法:
form = TaskForm(contact, instance=task, prefix='form', initial = {'contact' : contact.pk})
形式:
class TaskForm(ModelForm):
def __init__(self, contact, *args, **kwargs):
super(TaskForm, self).__init__(*args, **kwargs)
class Meta:
model = Task
不起作用:
看法:
form = TaskForm(contact, instance=task, prefix='form')
形式:
class TaskForm(ModelForm):
def __init__(self, contact, *args, **kwargs):
super(TaskForm, self).__init__(*args, **kwargs)
if contact:
self.fields['contact'].initial = contact.pk
class Meta:
model = Task