简体   繁体   English

如何获取用户ID

[英]How to get user ID

I am working on a website using Django.我正在使用 Django 开发一个网站。 I'm having a difficult time playing around codes, how do I get the ID of a user without passing a primary key (id, pk) in the URL.我在玩代码时遇到了困难,如何在不传递 URL 中的主键(id,pk)的情况下获取用户的 ID。 My code below does not give me a solution to getting the ID of a particular user.我下面的代码没有为我提供获取特定用户 ID 的解决方案。 When I print (user) it prints the current user logged in. Is there a way to get the ID of other users?当我打印(用户)时,它会打印当前登录的用户。有没有办法获取其他用户的 ID?

def home(request):
    p=Profile.object.filter(user=request.user)
    u=p.user
    send_request=FriendRequest.objects.filter(from_user=p.user)

def send_request(request, id):
    user=get_object_or_404(User, id=id) 
    frequest=FriendRequest.get_or_creat(from_user=request.user, to_user=user).first()

    path('home', home_view, name='home')

<a href='{% url 'site:send_request'  profile.user.id %}'>Add friend<a>

Use a form with POST method and send the user_id as a parameter but hidden to the user.使用带有 POST 方法的表单并将 user_id 作为参数发送但对用户隐藏。

<form method="post" action="{% url 'your_url' %}">
    {% csrf_token %}
    <input type="hidden" name="user_id" value="{{ user_id }}" />
    <button type="submit">Add Friend</button>
</form>

You can access the parameter in the view like this您可以像这样访问视图中的参数

request.POST.get('user_id')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM