Django formset和foreignkey保存

时间:2013-01-31 22:12:44

标签: django formset

我几乎尝试了我在互联网上发现的每一个想法,但它仍然没有用,

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对象'“:”RankedSkill.skill“必须是”技能“实例。”

1 个答案:

答案 0 :(得分:1)

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

你需要......

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

        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()

还有一件事......你应该修复你的formset验证:

if formset.is_valid: 
               #^^^ you need to call is_valid() or this will always return True.