[Answer]-Django foreign key is not set and hence unable to save form

1๐Ÿ‘

โœ…

Iโ€™m assuming you do not want to display the product field on the form, so you should exclude it from the form so the validation will pass:

class ResourceForm(forms.ModelForm):
    resource = forms.MultipleChoiceField(choices=ProductResource.CHOICES, widget = forms.CheckboxSelectMultiple)
    class Meta:
        model = ProductResource
        exclude = ['product']

Then in the view, just set the product manually after calling is_valid(). Just be sure to pass commit=False on the form.save() so that it will not actually save to the database until after you set the product. For example

...
saved_publication = publications_form.save()

resource_form = ResourceForm(request.POST)
if resource_form.is_valid():
    resource = resource_form.save(commit=False)
    resource.product = saved_publication
    resource.save()
๐Ÿ‘คjproffitt

Leave a comment