[Answer]-Django formset and foreignkey save

1👍

Your SkillRankForm is accepting strings instead of PKs or instances.

You need to either…

Modify the form to use PKs and not Text such as with skills = forms.ModelChoiceField
Or coerce the incoming string into a Skill object in your form (or view, even).

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

Also one more thing… you should fix your formset validation:

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

Leave a comment