0
我幾乎試過,我發現在互聯網上每一個想法,但現在還沒有工作,Django的表單集和外鍵保存
class RankedSkill(models.Model):
RANK_CHOICES = (
(1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5),
(6, 6),
(7, 7),
(8, 8),
(9, 9),
(10, 10),
)
skill = models.ForeignKey(Skill, related_name='ranks')
rank = models.IntegerField(max_length=2, choices=RANK_CHOICES)
assessment = models.ForeignKey(Assessment, related_name='skill_ranks')
)
評估和技能是另一種模式。在我的應用程序中,我想創建每種技能的表單來對它們進行排名。我使用了django formset,我用Skill.objects.all()獲得的初始數據創建了一個來自RankingSkillForms的formset。
skills = Skill.objects.all()
SkillFormSet = formset_factory(SkillRankForm, max_num=skills.count())
if request.method == 'POST':
formset = SkillFormSet(request.POST)
if formset.is_valid:
person = get_object_or_404(People, id=person_id)
assessment = Assessment.objects.create(supervisor=request.user, employee=person)
for form in formset.forms:
ranked_skill = form.save() # error coming from here
ranked_skill.assessment = assessment
ranked_skill.save()
else:
return render(request, 'people/make_assessment.html', {'formset': formset})
else:
initial = []
for skill in skills:
initial.append({'skill': skill})
formset = SkillFormSet(initial=initial)
return render(request, 'people/make_assessment.html', {'formset': formset})
一切工作正常,直到我試圖保存。
它將初始數據(Skill)作爲u'Skill Object的字符串。 (我刪除了unicode,因爲在這個技能名稱之前,而不是u'Skill Object'字符串)
錯誤消息是「Can not assign」u'Skill object'「:」RankingSkill.skill「必須是「技能」實例。「
哦,謝謝大家的驗證,但現在我得到在該步驟同樣的錯誤。 – grgizem
謝謝你的回答。我在表單技巧= forms.ModelChoiceField中進行了這些更改,之後我使charfield設置了可編輯的False。顯然我應該找到另一種可編輯的解決方案。 :) – grgizem