Tuesday, August 25, 2020

Re: def__str__(self) not working properly

0

Do this.

def __repr__ (self): return self.title

restart the shell/session.

then check.

i had this issue. only after restarting the section it worked 


On Sunday, 16 September 2018 at 17:14:18 UTC+5:30 Daniel Herrera wrote:
I was having the same issue, as mentioned above, it was a mere indentation problem, make sure the def __str__ is properly indented inside of the class and not at the same level.


On Friday, July 1, 2016 at 5:52:12 PM UTC+8, gary719_list1 wrote:
Hi all;

I am working on the official django tutorial
(https//docs.djangoproject.com/en/1.9/intro/tutorial/02/) on the section
that is adding the choices. Specifically:


# Create three choices.
 >>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
 >>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
 >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)

The "Not much" entry should return <Choice: Not much> but returns
<Choice: Choice object> instead.

This would seem to be a problem with the models.py def__str__(self)
call, but I can't locate the problem. Question class works fine. The
specific code is :

import datetime

from django.db import models
from django.utils import timezone


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

     def __str__(self):
         return self.question_text

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


class Choice(models.Model):
     question = models.ForeignKey(Question, on_delete=models.CASCADE)
     choice_text = models.CharField(max_length=200)
     votes = models.IntegerField(default=0)

     def __str__(self):
         return self.choice_text

OS Debian Stretch
KDE Desktop
Django 1.9
python 3.5
Eclipse PyDev IDE

All migrations are up to date.

Any help will be sincerely appreciated.

Gary R.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/685d0319-ecce-4ece-919c-ce6ea46a3cfan%40googlegroups.com.

No comments:

Post a Comment