I'm new to Django and I've correctly created a login/register and my account page. Now my problem is that no matter which user is logged in when it goes to my account page, the URL will also be ./account
Is there a way to pass which user is requesting the page and change the URL according to it but always pointing to the same template?
For instance, if the user logged in has username john clicking on my account it redirects to ./account/john but shows the same template. Basically I would like that the URLs reflect the user logged in
Currently, I manage the My account page as below.
navbar.html
{% if user.is_authenticated %}
<li >
<a href="{% url 'account' %}">
<i class='bx bxs-user-detail icon' ></i>
<span >My profile</span>
</a>
</li>
urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('account', views.account_user, name="account"),
]
CodePudding user response:
You can do this by incorporating a key to identify the user in the url structure. This requires changes in three places: 1. navbar.html, 2. urls.py, 3. views.py. See a suggestion for 1. and 2. below.
navbar.html
{% if user.is_authenticated %}
<li >
<a href="{% url 'account' user.user_name %}">
<i class='bx bxs-user-detail icon' ></i>
<span >My profile</span>
</a>
</li>
urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('account/<str:user_name>/', views.account_user, name="account"),
]
views.py
def your_view(request):
context = {}
..
# pass user object to context
context['user'] = request.user
# then pass context to the view
def account_user(request, user_name):
# use user_name to update querysets or context
However, if I correctly understand what you are trying to accomplish (i.e. you want to personalise the 'account' page to each user), I would approach it differently, namely by incorporating the user specific data in the 'account_user' view. You can do this by accessing the request.user object. This way you do not need to rework the url structure (saving you the steps outlines above).
views.py
def account_user(request):
context = {}
..
# pass user object to context
context['user'] = request.user
# filter any queries using the request.user object
# then pass context to the view
CodePudding user response:
Basically you need 2 views. One view is account/ which looks at request.user and then returns a 302 to redirect the user to the appropriate page (ex. John is logged in and is redirected to /account/john/). The other view being the account display which is account/<slug:username>/ and shows the account information for the passed in username.
However, you could also just make the link in navbar.html point directly to /account/john/ since the person is logged in and you have that information available.
