Grak
Grak

Reputation: 99

Django Attribute Error: object has no attribute '__state' and removing __init__ from Class

I'm trying to create a model for a sample Django application "webshop", and I'm having trouble at understanding what my problems stem from.

The models.py I have is:

from django.db import models

class Product(models.Model):

    def __init__(self, title, quantity, description, image_url=""):
        title = models.CharField(max_length=255)

        self.quantity = quantity
        self.title = title
        self.description = description
        self.image_url = image_url
        
    def sell(self):
        self.quantity = self.quantity - 1

and what I want to be able to do with it is to initialize it with something like:

toy1 = Product(title="Bear plush", description="Fluffy bear plush toy", quantity=10)

I can call it with

print(toy1.quantity) print(toy1.title) toy1.sell() and so on fine, but doing toy1.save() returns the error

AttributeError: 'Product' object has no attribute '_state'

Upon googling about the problem, I came across the fact that it's not advised to use init here, but the offered alternatives in https://docs.djangoproject.com/en/1.11/ref/models/instances/#creating-objects both utilize a logic where the first call of the class function is different from the initial call.

If the problem I'm facing is due to relying in __init__, how can I get rid of it while still being able to initialize the objects with toy1 = Product(title="Bear plush", description="Fluffy bear plush toy", quantity=10) or is my problem something completely different?

Upvotes: 2

Views: 1964

Answers (1)

paleolimbot
paleolimbot

Reputation: 436

I think the model you are trying to create should look like:

class Product(models.Model):
    title = models.CharField(max_length=255)
    quantity = models.IntegerField()
    description = models.TextField()
    image_url = models.CharField(max_length=255, validators=[URLValidator()])

    def sell(self):
        self.quantity = self.quantity - 1
        self.save()

Django takes care of the instantiation, so you don't need the __init__ bit.

Upvotes: 1

Related Questions