django use mixin needs to have a value for field “id” before this many-to-many relationship can be used

I’m trying to save a M2M object ( set it to a default value which is the one with position= 1 ) when I login with by admin is ok.

The problem I’m getting the following error:

needs to have a value for field “id” before this many-to-many relationship can be used

Models.py

class Categorymodel(models.Model):
    title=models.CharField(max_length=100)
    slug=models.CharField(max_length=100,unique=True)
    status=models.BooleanField(default=True)
    position=models.IntegerField()

    def __str__(self) -> str:
        return self.title

class Reportmodel(models.Model):
    subject=models.CharField(max_length=100)
    category=models.ManyToManyField(Categorymodel,related_name='info')
    user=models.ForeignKey(User,on_delete=models.CASCADE)

Mixin.py

class FormValidMixin():
    def form_valid(self,form):
        if self.request.user.is_admin:
            form.save()
    
        else:
            category1=(Categorymodel.objects.get(position=1))               
            self.obj=form.save(commit=False)  
            self.obj.user=self.request.user                                                                                                 
            self.obj.category.set(category1)

Answer

You should first save the self.obj object before you can alter its many-to-many relation, so:

category1 = Categorymodel.objects.get(position=1)
form.instance.user = self.request.user
self.obj=form.save()  # ← save the object
self.obj.category.set([category1])  # ← use a list