我正在尝试在创建视图中自动填充ForeignKey字段。当我尝试传递站点ID并在提交时保存它时,我会收到此错误。
Cannot assign "u'2'": "FireAlarm.site" must be a "Site" instance.
models.py
class Site(models.Model):
...
class FireAlarm(models.Model):
site = models.ForeignKey(Site)
...
urls.py
url(r'^(?P<site>[0-9]+)/create/$', FireAlarmCreate.as_view(), name='fire-alarm-create'),
views.py
class FireAlarmCreate(CreateView):
model = FireAlarm
form_class = FireAlarmForm
queryset = FireAlarm.objects.all()
success_url = '/sites/list'
def form_valid(self, form):
fire_alarm = form.save(commit=False)
fire_alarm.site = self.kwargs['site']
return super(FireAlarmCreate, self).form_valid(form)