Home > Software engineering >  django cannot assign must be an instance
django cannot assign must be an instance

Time:08-01

I'm trying to insert an item. but it's throwing

`Cannot assign "'2003-221'": "ClearanceItem.recorded_by" must be a "ClearanceCustomuser" instance.`

models.py

class ClearanceItem(models.Model):
cl_itemid = models.CharField(primary_key=True, max_length=20)
studid = models.CharField(max_length=9, blank=True, null=True)
office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True)
sem = models.CharField(max_length=1, blank=True, null=True)
sy = models.CharField(max_length=9, blank=True, null=True)
remarks = models.TextField(blank=True, null=True)
resolution = models.TextField(blank=True, null=True)
resolve = models.BooleanField(blank=True, null=True)
resolve_date = models.DateField(blank=True, null=True)
resolve_by = models.CharField(max_length=8, blank=True, null=True)
recorded_by = models.ForeignKey('ClearanceCustomuser', models.DO_NOTHING, 
db_column='recorded_by', blank=True,
                                null=True)
record_date = models.DateField(default=datetime.now, blank=True, null=True)

class Meta:
    managed = False
    db_table = 'clearance_item'

class ClearanceCustomuser(models.Model):
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_superuser = models.BooleanField()
userid = models.CharField(primary_key=True, max_length=9)
email = models.CharField(unique=True, max_length=254)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()

class Meta:
    managed = False
    db_table = 'clearance_customuser'

views.py

class Add(LoginRequiredMixin, CreateView):
form_class = CreateForm
model = ClearanceItem
template_name = 'clearance/add.html'

def form_valid(self, form):
    instance = form.save(commit=False)
    instance.recorded_by = self.request.user.userid
    instance.save()
    return HttpResponseRedirect(self.get_success_url())

search few related question Cannot assign must be a instance. Django and someone answer that Scripter.title is a foreign key to Book, so you must give it an actual Book, not a string.

I believe I am giving my clearanceitem an actual user which is userid = 2003-221. I dont understand why it's giving me an error

hope someone can help

edit: is it because userid is char(9) and recorded_by is char(8) is there a difference?

CodePudding user response:

Try this:

class Add(LoginRequiredMixin, CreateView):
   form_class = CreateForm
   model = ClearanceItem
   template_name = 'clearance/add.html'

   def form_valid(self, form):
      instance = form.save(commit=False)
      instance.recorded_by = ClearanceCustomuser.objects.get(userid=self.request.user.userid)
      instance.save()
      return HttpResponseRedirect(self.get_success_url())
  • Related