Django获取不是当前用户的用户的ID

问题描述:

我已经搜索了这个问题的答案,并且有很多关于如何获取已登录用户的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 

我假设作者有用户的关系。

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

它们是无关的。我想看看是否有可能,因为我创建了从作者到用户的外键,但是当我从表单保存POST数据时,这会在视图中创建各种问题。我已经更新了上面的原始问题,以显示我如何解决这个问题。 –