简体   繁体   English

如何在Django中登录用户ID

[英]How to get logged in user id in Django

I am very new in Python and Django. 我是Python和Django的新手。 A am trying to make app but I have an issue. 我正在尝试制作应用,但我遇到了问题。 Can anyone help me, please xD I can't get id of authenticated user... I tried it in this way, and many other ways... 任何人都可以帮助我,请xD我无法获取经过身份验证的用户的ID ...我以这种方式尝试了此操作,还有许多其他方式...

views.py views.py

class CreateProfile(CreateView):
    template_name = 'layout/add_photo.html'
    model = Profile
    fields = ['image', 'user']

html html

<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="text" name="username"> #Here has to be field filled in with logged in user
    <input type="file" name="image"> 
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-success">Save Changes</button>
        </div>
    </div>
</form>

And when I'm starting app, and want to change/add picture, I can do it for anyone from my database, not only for logged in user. 当我启动应用程序并想要更改/添加图片时,我可以为数据库中的任何人执行此操作,不仅限于登录用户。 enter image description here 在此处输入图片说明

Thanks for patience and help! 感谢您的耐心配合和帮助!

In the Django ClassBasedViews you can get your user's id as self.request.user.id and in your template as {{ user.id }} 在Django ClassBasedViews中,您可以将用户的ID获取为self.request.user.id并在模板中将其获取为{{ user.id }}

To check if someone is authenticated you can use self.request.user.is_authenticated() and in your template {% if user.is_authenticated %} .. {% endif %} 要检查某人是否已通过身份验证,可以使用self.request.user.is_authenticated()并在模板中使用{% if user.is_authenticated %} .. {% endif %}

class CreateProfile(CreateView):
    template_name = 'layout/add_photo.html'
    model = Profile
    fields = ['image', 'user']

    # For example, if you want to return to a certain user
    # profile (which requires url adjustments to take a Primary Key)
    def get_success_url(self):
        user_id = self.request.user.id # Get user_id from request
        return reverse_lazy('git_project:user_profile', kwargs={'id': user_id})

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

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