Reputation: 39
I am making website with Django. I want each user to have their own URL, so if a user with the username "john" registers, the URL will be .../user/john or if a user with the username "tim" registers, the URL will be .../user/tim. I also want that when I log in as "tim" and enter .../user/john in the search, I will see John's page.
This is my urls.py file:
from django.contrib import admin
from django.urls import path, include
from webapp.views import welcome_page, register, user_page, settings, timeline
urlpatterns = [
path('admin/', admin.site.urls),
path("", welcome_page, name="welcome_page"),
path("register/",register, name="register" ),
path("", include("django.contrib.auth.urls"), name="login_logout"),
path("user/",user_page, name="user_page"),
path("settings/", settings, name="settings"),
path("main/", timeline, name="main_timeline"),
]
And this is my views.py file:
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from .forms import RegisterForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
def welcome_page(response):
return render(response,"welcome.html")
def register(response):
error = ""
if response.method == "POST":
form = RegisterForm(response.POST)
if form.is_valid():
form.save()
return redirect("/login")
else:
error = form.errors
form = RegisterForm()
return render(response, "register/register.html", {"form":form, "error" : error})
@login_required
def user_page(response):
username = str(User.objects.get(username=response.user.username))
userphoto = username[0:2]
return render(response, "user_page.html", {"userphoto": userphoto})
@login_required
def settings(response):
return render(response, "settings.html")
@login_required
def timeline(response):
return render(response, "timeline.html")
Upvotes: 0
Views: 1555
Reputation: 4779
You need to create a URL path that accepts a username
.
path("user/<str:username>/",user_page, name="user_page"),
Now your view accepts the username that is passed as part of the URL.
def user_page(response, username):
# Your view logic goes here..
If you want to navigate to other users page then you could pass their username in url like this:
{% url 'user_page' username %}
Upvotes: 2
Reputation: 999
You need to use Django's url parameters as the following
...
path("user/<username>",user_page, name="user_page"),
...
And you intercept the username in your views by passing it as parameter as below
@login_required
def user_page(response, username):
...
Kindly check the docs for more details
Upvotes: 0