我正在尝试制作推特克隆,这是我试图发送推文时的问题。
模型
class Tweet(models.Model):
text = models.CharField(max_length=140)
date = models.DateField(default=date.today)
user = models.ForeignKey(User, unique=True)
表格
class TweetForm(forms.ModelForm):
class Meta:
model = Tweet
exclude = ["user", 'date']
现在我正在尝试将用户添加到推文信息mannualy,但得到错误:'User' object does not support indexing
以下是观点:
if request.method == 'POST':
form = TweetForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
author = form.save(commit=False)
author.user = UserProfile.objects.get(request.user) #HERE ASIGNING THE USER
author.save()
如何核心地将用户分配给推文?
答案 0 :(得分:4)
只要您的Author
模型类具有您正在使用的AUTH_USER_MODEL
的外键(默认为auth.User
),该行:
author.user = UserProfile.objects.get(request.user)
应该是:
author.user = request.user