[Django]-Django error: needs to have a value for field "…" before this many-to-many relationship can be used

43👍

Ok, the code is slightly messy, I’m sure you’ll be better off tackling your problem with ModelForms. Seems to me the problem actually is the line:

s.survey = self.survey

because s object hasn’t been written to the database yet, so accessing it’s survey ManyToMany field can yield problems. If you want to copy the same set of surveys from self to s you should do it iterating over them like this:

If this yields the same error, then try to do s.save() first and later copy the items:

s.save()
for item in self.survey:
    s.survey.add(item)

Your code is likely to remain like this:

def save(self, commit=True):
    s = SurveyThread()
    # these fields aren't problematic
    s.email = "test@test.com"
    s.comment = self.cleaned_data['comment']
    # you can add s.save() here to remove problems associated with object 
    # not yet persisted
    # s.save()
    for item in self.survey:
        s.survey.add(item)
    if commit:
        s.save()
    return s

I can see you have a if commit: to persist the object, so try to accommodate the code to make use of it. If the first version of my answer worked then you’ll be fine with the s.save() at the end, if the second is the one who worked, then you’ll have to adjust the code a little to stick to the commit value.

Hope this helps!

4👍

In this part of the code in forms.py, you’re setting the survey field on the SurveyThread object to None, yet it’s not allowed to be None according to your models.py:

def save(self, commit=True):
    s = SurveyThread()
    s.survey = None     ### This is the problem
    s.email = "test@test.com"
    s.comment = self.cleaned_data['comment']

    if commit:
        s.save()
    return s

You have to set survey to a SurveyResult object before you can save it, or allow it to be None in the model.

I think you want to change it to say:

s.survey = self.survey
👤Ben

Leave a comment