2016-05-16 43 views
0

我已經搜索了這個問題的答案,並且有很多關於如何獲取已登錄用戶的ID,所有在模板中需要的都是{{user.id }}。 我有一個論壇{{item.author}}中的帖子的作者姓名。此作者不是登錄用戶。 是否有可能不需要在視圖中查詢作者的ID?Django獲取不是當前用戶的用戶的ID

我曾嘗試使用外鍵將topicmodel和用戶模型關聯起來,但這給我帶來了一個問題,我在其中將主題和帖子保存在一起。我沒有正確創建實例。這裏是我不能去上班的觀點,

def topic_form(request): 
    if request.method == "POST": 
     userInstance = get_object_or_404(User, username = request.user) 
     Tform = TopicForm(request.POST) 
     Pform = PostForm(request.POST, instance=userInstance) 
     if Tform.is_valid() and Pform.is_valid(): 
      tform = Tform.save(commit=False) 
      tform.topicAuthor = request.user 
      tform.author = userInst #this needs to be a user instance 
      tform.save() #returns request and id 
      pform = Pform.save(commit=False) 
      pform.topic = tform 
      pform.author = request.user 
      pform.pub_date = timezone.now() 
      pform.save() 
      return redirect('init') 
    else: 
     topicform = TopicForm() 
     postform = PostForm() 
    return render(request, 'new_topic.html', {'topicform': topicform, 'postform': postform}) 

這些模型

class TopicModel(models.Model): 
    topic = models.CharField(max_length = 100) 
    topicAuthor = models.CharField(max_length = 100) 
    author = models.ForeignKey(User, related_name = 'id_of_author') 
    views = models.PositiveIntegerField(default = 0) 

    def __str__(self):    # __unicode__ on Python 2 
      return self.topic 

class PostModel(models.Model): 
    post = HTMLField(blank = True, max_length = 1000) 
    pub_date = models.DateTimeField('date published') 
    author = models.CharField(max_length = 30) 
    topic = models.ForeignKey(TopicModel, related_name = 'posts') 

    def __str__(self):    # __unicode__ on Python 2 
      return self.post 

回答

2

我假設作者有用戶的關係。

{{item.author.user.id}} 
+0

它們是無關的。我想看看是否有可能,因爲我創建了從作者到用戶的外鍵,但是當我從表單保存POST數據時,這會在視圖中創建各種問題。我已經更新了上面的原始問題,以顯示我如何解決這個問題。 –