Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In django, __init__ function on Model, causes attribute error, cannot save to database

Tags:

django

I am using django and a model definition such as

class Question(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    order = models.IntegerField()

    def __init__(self, *args, **kwargs):
        self.title = kwargs.get('title','Default Title')
        self.description = kwargs.get('description', 'DefDescription')
        self.order = kwargs.get('order', 0)

Attempting to call save() on an object of the question class, causes the shell to respond with

/django/db/utils.py", line 133, in _route_db
    return hints['instance']._state.db or DEFAULT_DB_ALIAS
AttributeError: 'Question' object has no attribute '_state'

However, removing the _____init_____ function, makes everything ok again. Any idea on what causes this and how to resolve it?

many thanks

like image 981
jcage Avatar asked Jul 06 '10 05:07

jcage


1 Answers

You need to call the superclass' __init__ method at some point in your subclass' __init__ method:

def __init__(self, *args, **kwargs):
    super(Question, self).__init__(*args, **kwargs)
    # your code here
like image 105
Joseph Spiros Avatar answered Nov 15 '22 04:11

Joseph Spiros