[Fixed]-Cannot assign must be a instance. Django


Of course. Not sure where the confusion here is. Scripter.title is a foreign key to Book, so you must give it an actual Book, not a string.


First, while this is not your question, i believe you missed something. If I understand correctly, you wish Scripters to have MULTIPLE books. Now, with your models, they can only have one book. If I’m correct as of what you are trying to achieve, your model should rather look like this:

class Book(models.Model):
  script_title = models.CharField(max_length=100)
  scripter = models.ForeignKey(Scripter)#A book "remembers" who wrote it

  def __unicode__(self):
    return self.script_title

class Scripter(models.Model):
  user = models.OneToOneField(User)
  name = models.CharField(max_length=30)
  #Scripter can write multiple books, can't he? So the next line is removed,
  #replaced by an extra line in Book class

  # title = models.ForeignKey(Book, null=True, blank=True, default=None)

Then you would access Scripter’s books like this:

scripter = Scripter.objects.get(name="joshua")
books = scripter.book_set.all() #all books written by joshua

As for your question, in current form, you would need to do something like this:

book = Book.objects.get(script_title="some_title")
scripter.title = book

But as I said before, you need to change your model structure, so you will be rather doing:

scripter = Scripter.objects.get(name="joshua")
book = Book.objects.Create(script_title="some title",scripter=scripter)


You dont have primary key in your book model

    class Book(models.Model):
script_title = models.CharField(primary_key = True,max_length=100)

def __unicode__(self):
    return self.script_title

This should work

Leave a comment