Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with _unicode() method in django

Tags:

django

I'm adding a unicode() method to my model, however when displaying all objects in the interactive it's not working.

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

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def _unicode_(self):
        return self.question
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def _unicode_(self):
        return self.choice
# Create your models here.

(InteractiveConsole

>>> from polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: Poll object>]
like image 686
fpena06 Avatar asked Sep 01 '26 10:09

fpena06


1 Answers

They need to be named __unicode__ (two underscores on either side). This is an awkward detail of Python reserved methods that is not immediately obvious by looking at them.

like image 154
Andrew Gorcester Avatar answered Sep 04 '26 20:09

Andrew Gorcester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!