Remi
Remi

Reputation: 3

How to save ForeignKey in queryset? 'NoneType' object has no attribute 'myfield'

How to save ForeignKey in queryset?

class BookFile(models.Model):
   myfile = models.FileField(upload_to="mybooks")

class MyBook(models.Model):
    number = models.CharField(max_length=10)
    file = models.ForeignKey(BookFile)

My try in views:

bookfile = form.cleaned_data.get('bookfile')
mybook = MyBook.objects.create(number="5555")
mybook.file.myfile = bookfile
mybook.save()

Error:

'NoneType' object has no attribute 'myfile'

Upvotes: 0

Views: 205

Answers (1)

Julien Greard
Julien Greard

Reputation: 999

What do you get in bookfile ? Is it an object or an id ? If it's an id, you could try:

bookfile = form.cleaned_data.get('bookfile')
mybook = MyBook.objects.create(number="5555")

bookFileObject = BookFile.objects.create()
bookFileObject.myfile = bookfile
bookFileObject.save()
mybook.file = bookFileObject
mybook.save()

Upvotes: 1

Related Questions