这是我的模特:
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
我有一个简单的表格:
class NewsForm(ModelForm):
class Meta:
model = News
exclude = ('pub_date','author',)
我排除pub_date,因为默认情况下是设置,而作者因为它是当前用户。 但是如何将作者设置为当前登录用户?
答案 0 :(得分:2)
我建议覆盖save()
方法并将用户传递给它:
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',)