0

I need to make it so that when creating a new post in a blog using Django the admin (user) who's created it is set automatically as its author. This is my code so far (which doesn't work, the last line gives an error):

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True, blank=True)
    text = models.TextField()
    notable = models.BooleanField(default=False)
    created = models.DateTimeField(null=True, editable=False, blank=True)
    published = models.DateTimeField(
                blank=True, null=True)
    modified = models.DateTimeField(null=True, blank=True)
    tags = models.ManyToManyField(Tag, null=True, blank=True)

def save(self, *args, **kwargs):
    ''' On save, update timestamps '''
    if not self.id:
         self.created = datetime.today()
         self.slug = slugify(self.title)
    self.modified = datetime.today()            
    return super(User, self).save(*args, **kwargs)

Can anyone help me please?

There's a similar question here in Stack Overflow but it doesn't entirely answer my question as it still leaves the option to select another user and not have it set automatically, which is what I truly want.

Community
  • 1
  • 1
Gothbag
  • 11
  • 7
  • 2
    `return super(User, self).save(*args, **kwargs)` should be `return super(Post, self).save(*args, **kwargs)`. – Yaroslav Admin Aug 23 '15 at 10:50
  • 1
    Also you don't need to override `save()` to update timestamps. See [`auto_now`](https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.DateField.auto_now) and [`auto_now_add`](https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.DateField.auto_now_add). – Yaroslav Admin Aug 23 '15 at 10:53

0 Answers0