python - 如何在 Django 中获取登录用户 ID

标签 python django

我对 Python 和 Django 非常陌生。我正在尝试制作应用程序,但我遇到了问题。 任何人都可以帮助我吗,请xD 我无法获取经过身份验证的用户的 ID... 我尝试过这种方式,还有很多其他方式......

views.py

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

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>

当我启动应用程序并想要更改/添加图片时,我可以为数据库中的任何人执行此操作,而不仅仅是登录用户。 enter image description here

感谢您的耐心和帮助!

最佳答案

在 Django ClassBasedViews 中,您可以将用户的 id 获取为 self.request.user.id ,并在模板中将其获取为 {{ user.id }}

要检查某人是否经过身份验证,您可以使用 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})

关于python - 如何在 Django 中获取登录用户 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42369776/

相关文章:

python - Python 中的并行处理/线程

python - 展开字典的快捷方式

Django - 如何在生产服务器上运行它?

python - Pygame 旋转导致图像卡顿

python - 零维数组无法串联,但我的数组不是零维

python - 在循环中迭代字符串中的每个第 n 个元素 - python

python - 在 Django 中测试电子邮件发送

django,查询不同模型的好方法

Django REST 框架。更新获取空的validated_data

python - Django 。 View 中的 success_url 或模型中的 get_absolute_url() 。如何正确使用它们?