Django:如何在CreateView中自动填充ForeignKey

时间:2015-12-14 14:19:12

标签: django

我正在尝试在createview中自动填充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)

1 个答案:

答案 0 :(得分:2)

如错误所示,您无法将站点ID 2分配给外键。

您可以将ID分配给site_id

fire_alarm.site_id = self.kwargs['site']

首先从数据库中获取网站:

site = Site.objects.get(id=self.kwargs['site'])
fire_alarm.site = site