gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:15:46 26 4
gpt4 key购买 nike

我正在尝试自动填充 createview 中的外键字段。当我尝试传入站点 ID 并在提交时保存它时,出现此错误。

Cannot assign "u'2'": "FireAlarm.site" must be a "Site" instance.

模型.py

class Site(models.Model):
...

class FireAlarm(models.Model):
site = models.ForeignKey(Site)
...

url.py

url(r'^(?P<site>[0-9]+)/create/$', FireAlarmCreate.as_view(), name='fire-alarm-create'),

View .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)

最佳答案

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

您可以将 ID 分配给 site_id:

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

或者先从数据库中获取站点:

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

关于Django:如何在CreateView中自动填充ForeignKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34269244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com