0

Here's the issue I'm currently having:

  • I'm running through the first django tutorial on Windows using Command Prompt
  • I've created a table called 'Question' in models.py.
  • I'm attempting to create a __str__() function within this class like following:

.

from django.db import models
class Question(models.Model):
   def __str__(self):
     return self.question_text`

This is how my models.py looks:

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

The error I'm receiving is the following:

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 117, in __new__
kwargs = {"app_label": package_components[app_label_index]}
IndexError: list index out of range

Anyone got any idea? I'm a total noob to django, and I'm not 100% sure what base.py should be doing here.

Base.py can be found here: https://github.com/django/django/blob/master/django/db/models/base.py

1 Answer 1

1

you are almost there

you need to add the def __str__() method inside of the Question class inside of models.py file like.

your models.py should look like this:

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text
class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text #or whatever u want here, i just guessed u wanted choice text

what you are actually doing is overriding a built in dunder method in a class you are subclassing. models.Model itself has a __str__ method inside it already, and you are just modifying its behavior in your Question version of models.Model

PS. the method name should be __unicode__ instead of __str__ if you are on python 2

PPS. a little bit of OOP language: if a "function" is part of a class, it is called a "method"

Sign up to request clarification or add additional context in comments.

1 Comment

it happens, check out this article on sublcassing/inheritance, because often it helps to see WHY you are doing something to understand why its not working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.