gpt4 book ai didi

django - 值错误 : Cannot assign : must be an instance

转载 作者:行者123 更新时间:2023-12-05 07:20:46 29 4
gpt4 key购买 nike

所以我是 Django 的新手,我正在尝试保存一个模型 Ovelse 的新实例,它有一个指向另一个模型 Okt 的外键。我有一个 View ,其中包含所有 Okt 实例的列表,该列表链接到连接到每个 Okt 的所有 Ovelse 实例。

模型.py

class Okt(models.Model):

def __str__(self):
return '{}, uke {}, dag {}'.format(self.sykel_navn, self.sykel_uke, self.sykel_dag)


sykel_navn = models.CharField(max_length=8, default="Sykel 1")
sykel_dag = models.CharField(max_length=(1), choices=(SYKEL_DAGER))
sykel_uke = models.CharField(max_length=(1), choices=(SYKEL_UKER))
dato = models.DateTimeField('Dato på treningsøkt: ')
notater = models.CharField(max_length=400)


class Ovelse(models.Model):

okt = models.ForeignKey(Okt, on_delete=models.CASCADE)
ovelse_type = models.CharField(max_length=2, choices=MUSKELGRUPPE_CHOICES)
ovelse_navn = models.CharField(max_length=20)
vekt = models.IntegerField(default=0, name='kg')
sets = models.PositiveIntegerField(default=2)
reps = models.PositiveIntegerField(default=2)

def __str__(self):
return self.ovelse_navn

View .py

class OvelseCreateView(generic.CreateView):
model = Ovelse
template_name = 'trening/add.html'
form_class = OvelseForm

def form_valid(self, form):
form.instance.okt = self.kwargs.get('pk')
return super(OvelseCreateView, self).form_valid(form)

表单.py

class OvelseForm(forms.ModelForm):

class Meta:
model = Ovelse
exclude = ['okt',]
fields = ['ovelse_navn', 'ovelse_type', 'kg', 'sets', 'reps']

def __init__(self, *args, **kwargs):
super(OvelseForm, self).__init__(*args, **kwargs)
self.fields['ovelse_type'].label = "Muskler brukt"
self.fields['ovelse_navn'].label = "Navn på øvelsen"
self.fields['kg'].label = "Antall kilo"
self.fields['sets'].label = "Antall set"
self.fields['reps'].label = "Antall reps"

当我尝试提交表单时,收到错误消息:无法分配“1”:“Ovelse.okt”必须是“Okt”实例,而我希望创建该实例的新模型。

最佳答案

由于您正在“注入(inject)”主键本身,而不是 Okt 对象,因此您应该使用 .okt_id 而不是 .okt:

class OvelseCreateView(generic.CreateView):

model = Ovelse
template_name = 'trening/add.html'
form_class = OvelseForm

def form_valid(self, form):
form.instance.<b>okt_id</b> = self.kwargs.get('pk')
return super(OvelseCreateView, self).form_valid(form)

请注意,您可以在表单的 Meta 类中设置标签,为此无需覆盖 __init__ 文件:

class OvelseForm(forms.ModelForm):

class Meta:
model = Ovelse
exclude = ['okt',]
fields = ['ovelse_navn', 'ovelse_type', 'kg', 'sets', 'reps']
<b>labels</b> = {
'ovelse_type': 'Muskler brukt',
'ovelse_navn': 'Navn på øvelsen',
'kg': 'Antall kilo',
'sets': 'Antall set',
'reps': 'Antall reps'
}

关于django - 值错误 : Cannot assign : must be an instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57347374/

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