Chad
Chad

Reputation: 2071

Adding a computed default value to Django model, how?

I'm trying to learn Python and Django by implementing an online forum. Right now, I'm trying to set the default value of the post title to "Re:" + thread.title, but I can't seem to do it.

I've searched for anything like this but nothing seems to answer my problem.

Here's my code (models.py):

from django.db import models

class Thread(models.Model):
    title = models.CharField(max_length=50)

    def __unicode__(self):
        return u'[id=%s]%s' % (self.id, self.title)

class Post(models.Model):
    thread = models.ForeignKey(Thread)
    title = models.CharField(max_length=50)
    post_date = models.DateTimeField(auto_now_add=True)
    content = models.TextField()

    def __init__(self):
        super(Post, self).__init__()
        if not self.title:
            self.title = "Re: %s" % self.thread.title

    def __unicode__(self):
        return u'%s::[id=%s]%s' % (self.thread, self.id, self.title)

I hope someone can help me.

Regards, Chad

Upvotes: 0

Views: 158

Answers (1)

wRAR
wRAR

Reputation: 25693

You probably want to set the default value in the overridden save method. Your __init__ code doesn't work because at that point self.thread is not set yet.

Upvotes: 1

Related Questions