0

我几乎尝试了我在互联网上找到的所有想法,但仍然无法正常工作,

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”实例。”

4

1 回答 1

1

SkillRankForm正在接受字符串而不是 PK 或实例。

你需要要么...

修改表单以使用 PK 而不是 Text,例如 withskills = forms.ModelChoiceField
或将传入的字符串强制转换为表单(或视图,甚至)中的技能对象。

        ranked_skill = form.save(commit=False)
        skill, created = Skill.objects.get_or_create(name=form.cleaned_data['skill'])  
                                           #^^^^ assuming there's a name field
        ranked_skill.skill = skill
        ranked_skill.save()

还有一件事......你应该修复你的表单集验证:

if formset.is_valid: 
               #^^^ you need to call is_valid() or this will always return True.
于 2013-01-31T22:20:46.613 回答