我几乎尝试了我在互联网上找到的所有想法,但仍然无法正常工作,
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,我从 RankedSkillForms 创建了一个 formset,其中包含通过 Skill.objects.all() 获得的初始数据。
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})
一切正常,直到我尝试保存。
它以 u'Skill Object' 字符串的形式获取初始数据(技能)。(我删除了 unicode,因为在该技能名称出现之前而不是 u'Skill Object' 字符串之前)
错误消息是“无法分配“u'Skill object'”:“RankedSkill.skill”必须是“Skill”实例。”