Leszek Wroński Leszek Wroński - 9 days ago 5
Python Question

"Cannot assign / must be an instance" error when creating a model instance from a CSV (ForeignKey related)

(I have read a few related questions, but none seems to have the answer for my particular problem, or perhaps I have misunderstood them.) In my app I have a model Kurs, and each Kurs is assigned to a user in this way:

class Kurs(models.Model):
prowadzacy = models.ForeignKey(User)


I want to populate my database of Kurs's from a CSV. The 0th element of each row is a username. So in my reader routine I wrote what follows (skipping the, I hope, irrelevant details):

n = Kurs()
n.prowadzacy = User.objects.get(username=row[0])


Now, in the shell, when I do this, what I'm getting is, I thought, a User instance:

>>> User.objects.get(username='leszekwronski')
<User: leszekwronski>


But when I run my reader routine it tells me it does not actually have a User instance to assign to the 'prowadzacy' field:

ValueError: Cannot assign "'leszekwronski'": "Kurs.prowadzacy" must be a "User" instance.


What am I doing wrong?

(I considered that maybe I'm getting the id of the User, so I also halfheartedly tried

n.prowadzacy = User.objects.get(id=User.objects.get(username=row[0]))`


but arrived at the same error.)

-------------------------- EDIT
This is my whole reader routine:

from .models import *

import csv

def importcourses(filename):
dataReader = csv.reader(open(filename), delimiter=';', quotechar='"')
for row in dataReader:
if row[0] != 'Username': # Ignore the header row, import everything else
n = Kurs()
n.prowadzacy = User.objects.get(username=row[0])
n.nazwa = row[1]
n.opis = row[2]
n.kategoria = Kategoria.objects.get(id=row[3])
n.semestr = Semestr.objects.get(id=row[4])
n.ects = row[5]
n.godziny = row[6]
n.kanon = row[7]
n.otwarty = row[8]
n.save()


I thought the details about other fields were not relevant...

----------------- EDIT 2
After RichSmith's comments below, I have added

from django.contrib.auth.models import User


to the reader routine. The error now changed to the following:

TypeError: int() argument must be a string or a number, not 'User'


and the error is assigned to the same line as before.

---------------------- EDIT 3:
Let this be a lesson to all of us newbies :-) After restarting the shell, everything is working. It seems RichSmith's idea was the needed fix!

Answer

are you importing User? from django.contrib.auth.models import User

Comments