因此,我对Django非常陌生,我正在尝试保存模型Ovelse的新实例,该实例具有指向另一个模型Okt的外键。我有一个视图,其中包含所有Okt实例的列表,该列表链接到连接到每个Okt的所有Ovelse实例。
Models.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
views.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)
forms.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”实例,而我希望创建该实例的新模型。
答案 0 :(得分:0)
由于您自己是在“注入”主键而不是 {
"entries": [
{
"jason": {
"added": true
}
}
]
}
对象,因此应在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.okt_id = self.kwargs.get('pk')
return super(OvelseCreateView, self).form_valid(form)
类中设置标签,而无需为此覆盖Meta
文件:
__init__