[英]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.