[Fixed]-ValueError: "needs to have a value for field "id" before this many-to-many relationship can be used"


You just need to edit your save method in your form,

def save(self, *args, **kwargs): 
    if not commit: 
        raise NotImplementedError("Can't create User and Userextended without database save") 
    user = super().save(*args, **kwargs)
    user_profile = Userextended(user=user, cristin=self.cleaned_data['cristin']) 
    return user

You need to save your UserExtended model first, then add the Rolle instances to the many to many relation.


If you’re using DRF you can use the validate method:

instead of this

    def create(self, validated_data):
        validated_data['slug'] = slugify(validated_data['name'])
        return budgets.models.BudgetCategory.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.slug = slugify(validated_data['name'])
        return instance

do this

def validate(self, data):
        data['slug'] = slugify(data['name'])
        return data


The error message happened because “rolle” should be specified as a many-to-one relationship and not a many-to-many. The model has been updated to the following and is now working perfectly:

class Userextended(models.Model):
    rolle = models.ForeignKey(Personrolle, models.SET_NULL, blank=True, null=True)

Leave a comment