简体   繁体   English

当没有给出 url 参数时,如何在 Django 视图中将当前登录的用户设置为默认值

[英]How do i set the current logged in user as default in Django view when no url parameters are given

i want the /profile/ route to be accessible without having to pass any url argument我希望无需传递任何 url 参数即可访问 /profile/ 路由

This is my profile View:这是我的个人资料视图:

@login_required
def profile(request, username):
    ctx = {"username" : username}
    return render(request, "raynet/profile.html",ctx)

This is my url pattern:这是我的网址模式:

urlpatterns = [
    path('', views.landing),
    path('home/', views.home),
    path('profile/', views.profile),
    path('profile/<username>', views.profile),
    path('apps/', views.apps),
    path('signin/', views.signin),
    path('signup/', views.signup),
    path('testing/', views.testing),
    path('signout/', views.signout),
]

It works fine if i specify a username in the url, but it doesnt work if i just go to /profile/ I want to get the current logged in user as default when no url variable is specified.如果我在 url 中指定一个用户名,它工作正常,但如果我只是去 /profile/ 它不起作用我想在没有指定 url 变量时将当前登录的用户作为默认值。

Try like this:像这样尝试:

@login_required
def profile(request, username=None):   
    ctx = {"username" : username if username else request.user.username}
    return render(request, "raynet/profile.html",ctx)

Here I am writing username parameter as keyword argument, so that username default value is None.在这里,我将用户名参数写为关键字参数,因此用户名默认值为 None。 Then using if else logic, I am assigning username value from argument or from request.user.username .然后使用 if else 逻辑,我从参数或request.user.username分配用户名值。

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

相关问题 Django - 如何将表单中的默认值设置为当前用户? - Django - How Do I Set A Default Value In A Form To Be The Current User? 我登出后如何在Django中呼叫预设的首页网址 - How to Call default home url in django when i logged out Django当我使用基于类的视图时,如何在表单中传递request.user(当前登录的用户)? - Django How I can pass request.user(current logged user) in forms when I use class based view? 如何在url上传递当前登录用户的用户名? python Django的 - How to pass ausername of the current logged in user on url? python django 获取当前登录的用户并在“模型” |“默认设置”中设置为默认用户 Django + Python3 - Get current logged in User and set as default user on Model | Django + Python3 Django-Rest 框架:如何从下拉列表中排除当前登录的用户 - Django-Rest Framework: How Do I exclude current logged in user from dropdown 当我在 Django 中运行服务器时如何设置默认 url - How to set the default url when i run server in Django 如何仅在Django中打印当前登录的用户数据? - How can I only print the the current logged in user data in Django? url 中的当前参数设置在下一个 url 中 django - Current parameters in url set in the next url in django 如何提取已登录用户的用户个人资料? Django的 - How do I pull the user profile of the logged in user? django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM