开发者

I need to setting author when saving model's instance

This is my model:

class News(models.Model):
开发者_开发技巧  title = models.CharField(max_length=250)
  text = models.TextField()
  pub_date = models.DateTimeField(default=datetime.datetime.now)
  author = models.ForeignKey(User)

  def __unicode__(self):
    return self.title

And I have a simple form for it:

class NewsForm(ModelForm):
    class Meta:
            model = News
            exclude = ('pub_date','author',)

I'm excluding pub_date because it's settings by default, and author because it will be current user. But how set author to current logged user?


I would recommend overwriting the save() method and passing the user to it like this:

class NewsForm(ModelForm):

    def save(self, author, commit=True):
        # Don't commit the results yet
        news = ModelForm.save(self, commit=False)
        news.author = author
        if commit:
            news.save()
        return news

    class Meta:
            model = News
            exclude = ('pub_date','author',)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜