I am following a lightbird tutorial on creating a forum with Django/Python. Here is the code to create a Thread
model.
class Thread(models.Model):
title = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
modified = models.DateTimeField(auto_now=True)
forum = models.ForeignKey(Forum)
def __unicode__(self):
return unicode(self.creator) + " - " + self.title
And a Post
model:
class Post(models.Model):
title = models.CharField(max_length=60)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
thread = models.ForeignKey(Thread)
body = models.TextField(max_length=10000)
def __unicode__(self):
return u"%s - %s - %s" % (self.creator, self.thread, self.title)
def short(self):
return u"%s - %s\n%s" % (self.creator, self.title, self.created.strftime("%b %d, %I:%M %p"))
short.allow_tags = True
I am having difficulty understanding the code after the unicode function! I have been using the unicode while creating model in a very simple form like:
class Post(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
I understand this but not the code in the models above. Could someone please explain it to me. Thank you!
unicode(self.creator) +\ #will call the __unicode__ method of the User class
' - ' +\ # will add a dash
self.title #will add the title which is a string
then for the second one
"%s"%some_var #will convert some_var to a string (call __str__ usually...may fall back on __unicode__ or something)
so
return u"%s - %s\n%s" % (self.creator, self.title, self.created.strftime("%b %d, %I:%M %p"))
will call the __str__
(or maybe __unicode__
)function on User class for the creator
then it adds a dash and the title
\n
is an end line
and strftime
will convert a timestamp into english "MonthAbbrv. Day, 24Hr:Minutes"