0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks wRAR. I'm curious would this be evident when adding things via the admin page?
@Chad no, but you don't have many other options, as self.thread is initially empty when creating object in admin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.