django获取当前用户id
我有一个迷你应用程序,用户可以登录、查看他们的个人资料并互相关注。 “关注”是一种类似于虚拟社区中常规“朋友”关系的关系,但它不一定是互惠的,这意味着一个人可以关注一个用户,而不需要用户去关注那个关注他的人。 我的问题是: 如果我是登录用户,并且导航到配置文件 X,然后按下“follow”按钮,我如何获取当前配置文件 ID?(当前配置文件意味着我(登录用户)现在正在查看的配置文件。 )
观点:
def follow(request):
if request.method == 'POST':
form = FollowForm(request.POST)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.initiated_by = request.user
u = User.objects. what here?
new_obj.follow = u
new_obj.save()
return HttpResponseRedirect('.')
else:
form = FollowForm()
return render_to_response('followme/follow.html', {
'form': form,
},
context_instance=RequestContext(request))
提前致谢!
i have a mini app where users can login, view their profile, and follow each other.
'Follow' is a relation like a regular 'friend' relationship in virtual communities, but it is not necessarily reciprocal, meaning that one can follow a user, without the need that the user to be following back that person who follows him.
my problem is:
if i am a logged in user, and i navigate to a profile X, and push the button follow, how can i take the current profile id ?(current profile meaning the profile that I, the logged in user, am viewing right now.)
the view:
def follow(request):
if request.method == 'POST':
form = FollowForm(request.POST)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.initiated_by = request.user
u = User.objects. what here?
new_obj.follow = u
new_obj.save()
return HttpResponseRedirect('.')
else:
form = FollowForm()
return render_to_response('followme/follow.html', {
'form': form,
},
context_instance=RequestContext(request))
thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
request.user.id
。但还有更好的做法。让我看看。http://docs.djangoproject.com/en/1.2/topics/db/ optimization/ 是一个好的开始,并且充满了好的实践。
对于您的情况,请使用
request.user.id
。Try
request.user.id
. But there is a better good practice. let me see.http://docs.djangoproject.com/en/1.2/topics/db/optimization/ is a good start and is full of good practice.
In your case, use
request.user.id
.如果您将用户的个人资料添加到表单中,则可以将其与帖子一起传递。
有多种方法可以做到这一点。您可以向您的 FollowForm 添加一个隐藏字段(将配置文件作为实例传递)。
您可以通过插入隐藏字段来更手动地完成此操作,例如:
然后您可以将上面的代码更改为:
或者,也许您的视图中已经有了配置文件的用户 ID?
If you add the user's profile to your form, you can pass it in with your post.
There are a number of ways to do it. You could add a hidden field to your FollowForm (pass in the profile as an instance).
You could do it more manually by inserting a hidden field such as:
Then you could change your code above to:
Or, perhaps you already have the profile's user id in your view?