Stack Exchange
Type Error : 'authors' is an invalid key argument for this function
I seriously dont know why i am getting a Type Error in this piece of django app. Below is my models.py code:
from django.db import models

# Create your models here.
class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=30)
    website = models.URLField()

    def __str__(self):
        return self.name

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField(verbose_name=' Your E-mail')

    def __str__(self):
        return "%s %s" %(self.first_name, self.last_name)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField(blank=True, null=True)

    def __str__(self):
        return self.title

I have created both the author object and publisher object from the shell named (mak & mas) respectively.
>>> from books.models import Publisher, Author, Book
>>> mak = Author.objects.create(first_name = "Kennedy")
>>> mas = Publisher.objects.create(name = "Dreem Inc")

But when i try to populate the Book database table, i get a Type Error:
>>> mybook = Book(title="The Prince", authors=mak, publisher=mas, publication_date = date(1989, 6, 30))

>>> Type Error : 'authors' is an invalid key argument for this function

I can easily populate the 'Publisher' and "Author" table.
Please any help on this?

Take a look at this topic : http://stackoverflow.com/questions/6996176/how-to-create-an-object-for-a-django-model-with-a-many-to-many-field

You can't assign ManyToMany field in the model's constructor.  Moreover you can't set the M2M field to unsaved instance.  So you have to save the instance first and then assign the M2M field:
mybook = Author.objects.create(title="The Prince", publisher=mas,
                               publication_date=date(1989, 6, 30))
mybook.authors.add(mak) # or mybook.authors = [mak]


Sorry @catavaran, i made a mistake earlier. I corrected it by doing this : >>> mybook = Book(title="The Prince", authors=mak, publisher=mas, publication_date = date(1989, 6, 30))



Type Error : 'authors' is an invalid key argument for this function



