Ricky
Ricky

Reputation: 13

Question about Django tutorial official part3 html code

I have a question about the js code when I'am learning on Django official tutorial part3. In the "Raising a 404 error" section, the official code use following code to display the "question_text" in object called "question":

{{ question }}

I don't understand why this code could work. The "question" is not a string but a object. It should be "question.question_text" .

views.py

def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})

models.py

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('datepublished')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now()-datetime.timedelta(days=1)

Besides, It works when I use the code {{ question.question_text }} So, I want to know why those two can have same output.

Upvotes: 1

Views: 140

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477308

Because you defined a __str__ for the object:

class Question(models.Model):

    # ...

    def __str__(self):
        return self.question_text

Django implicitly calls str(..) over the variables. In case you did not override the __str__ it would still render something: the __str__ of the superclass. The same happens for non-model objects (like ints, lists, tuples, custom class objects, etc.).

Since models by default have a __str__ that looks approximately like Model object (id), if you do not override the __str__ (nor some superclass in between), then it will thus render the object that way. So if you would not provide a __str__ yourself, it would look like Question object (123) (with 123 the id of the object).

Note that you by writing {{ question }} thus depend on the __str__ function: if you later change the __str__, the rendering will change. So in case you need the question_text, it is better to do this explicitly.

Upvotes: 1

Related Questions