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

11๐Ÿ‘

โœ…

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']) 
    user_profile.save() 
    user_profile.rolle.add(self.cleaned_data['rolle'])
    user_profile.save()
    return user

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

๐Ÿ‘คzaidfazil

1๐Ÿ‘

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'])
        instance.save()
        return instance

do this

def validate(self, data):
        data['slug'] = slugify(data['name'])
        return data
๐Ÿ‘คRio Weber

0๐Ÿ‘

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)
๐Ÿ‘คChristian

Leave a comment