我已经搜索了这个问题的答案,并且有许多关于如何获取登录用户的ID,模板中需要的只是{{user.id}}。 我在论坛中有一个帖子的作者姓名{{item.author}}。此作者不是登录用户。 是否有可能获得该作者的ID而无需在视图中进行查询?
我确实尝试使用外键来关联topicmodel和用户模型,但这给了我一个问题,我将一个主题和一个帖子保存在一起。我没有创建实例cotrrectly。以下是我无法开展工作的观点,
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
答案 0 :(得分:2)
我假设作者与用户有关系。
{{item.author.user.id}}