简体   繁体   English

Django:如何在基于 class 的视图中获取登录用户的用户名?

[英]Django: How do I get the username of the logged-in user in my class based view?

I have implemented a DeleteView and would like it to redirect it to the logged-in user's profile after deleting the object:我已经实现了一个 DeleteView 并希望它在删除 object 后将其重定向到登录用户的配置文件:

class DeleteAttendanceFeedItem(DeleteView, LoginRequiredMixin):
    model = AttendanceFeedItem
    template_name = "users/delete_attendance_feed_item.html"
    context_object_name = "attendance_feed_item"
    success_url = reverse_lazy("user_profile", kwargs={"username" : request.user.username})

I don't have access to the request object in a class-based view, though.不过,我无法在基于类的视图中访问请求 object。 Searching StackOverflow suggests I have access to self.request.user.username, but that's throwing the same error.搜索 StackOverflow 表明我可以访问 self.request.user.username,但这会引发相同的错误。

This seems like a very simple thing that I have burned a surprisingly large amount of time reading SO and Django documentation to absolutely no avail.这似乎是一件非常简单的事情,我花费了大量时间阅读 SO 和 Django 文档,但完全无济于事。 Help?帮助?

Use self.request.user.username to get the username inside the get_success_url() method使用self.request.user.usernameget_success_url()方法中获取用户名

class DeleteAttendanceFeedItem(DeleteView, LoginRequiredMixin):
    model = AttendanceFeedItem
    template_name = "users/delete_attendance_feed_item.html"
    context_object_name = "attendance_feed_item"

    def get_success_url(self): return reverse_lazy("user_profile", kwargs={"username": self.request.user.username})

暂无
暂无

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

相关问题 如何在 Django 中获取登录用户的用户名? - How can I get the username of the logged-in user in Django? 如何在Django views.py中获取登录用户的用户名 - How can I get the username of the logged-in user in Django views.py 在 Django 中,我如何知道当前登录的用户? - In Django, how do I know the currently logged-in user? 如何使用Django将一个页面显示给已登录的用户,将另一个页面显示给未登录的用户? - How do I show one page to logged-in user and another to a not-logged in user with Django? 如何过滤当前登录用户的 Django 表单下拉列表(基于类的视图) - How to filter Django Form dropdown for currently logged-in user (Class Based Views) 如何根据组显示与已登录用户有关的数据? - How do I present data relevant to the logged-in user based on Group? Django自定义管理器 - 如何仅返回登录用户创建的对象? - Django custom managers - how do I return only objects created by the logged-in user? 如何将登录用户的用户名添加到 django 中的模型字段 - How do I add username of logged in user to model field in django 如何在 Django 中获取登录用户的用户名? - How can I get the username of the logged in user in Django? 如何获取写入文本的登录用户的用户名并将其永久显示在 Django 中的文本旁边? - How do i get the username of a logged user writing a text and display it beside the text permanently in Django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM