Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django | <title> object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used

I get an error using with using form.save(commit=False) and I cannot figure out what I’m doing wrong.

My view looks something like this:

views.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def make_electable(request, election_id):
    election = get_object_or_404(CommissionElection, id=election_id)
    if request.method == 'POST':
        form = MakeElectable(request.POST)
        if form.is_valid():
            electable = form.save(commit=False)
            electable.election.set(election)
            form.save()

forms.py

class MakeElectable(forms.ModelForm):
    class Meta:
          model = ElectablePerson
          fields = ['commission',]
    commission = forms.ModelChoiceField(queryset=Commissie.objects.all(), widget=forms.RadioSelect())

models.py

class CommissionElection(models.Model):
    title = models.CharField(max_length=64)
    commission = models.ManyToManyField(Commissie)
    electable_time = DateRangeField()
    voting_time = DateRangeField()


class ElectablePerson(models.Model):
    commission = models.CharField(max_length=128)
    election = models.ManyToManyField(CommissionElection)

The error I get is:

"<ElectablePerson: ElectablePerson object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used.

I don’t see why the object is None. I suspect it has something to do with the manytomanyfield.

>Solution :

A many to many field is a table which uses ‘id_electable, id_election’ as keys, with commit=false, you don’t persist which gives you no id. Following code should fix your issue.

if form.is_valid():
    electable = form.save()
    electable.election.add(election)

Also see https://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.add for many to many relations.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading