我对 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/