2014-09-24 58 views
1

我試圖讓Twitter克隆,這是我試圖發送推文時的問題。'用戶'對象不支持索引

模型

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() 

如何正確分配用戶推文?

回答

4

只要你Author模型類有一個外鍵AUTH_USER_MODEL你使用(默認爲auth.User)行:

author.user = UserProfile.objects.get(request.user) 

應該是:

author.user = request.user