1

I have a customized user model like this:

class Utilisateur(models.Model):
    username = models.CharField(max_length=50)
    email = models.CharField(max_length=50)
    password = models.CharField(max_length=50)
    phone = models.CharField(max_length=80)

And I have my view declared this way:

def profile(request):
    return render(request, 'profile.html')

So I want my URL to appear with username in it, something like this : http://127.0.0.1:8000/profile/username1/

How can I pass the username to the URL?

2 Answers 2

4

Read the URL dispatcher documentation of django. It has covered most of the usage patterns.

https://docs.djangoproject.com/en/4.0/topics/http/urls/

In your urls.py you have to defined the variable part of the URL which should contain the username. Something like:

from django.urls import path

from .views import profile

urlpatterns = [
    path('profile/<str:username>/', profile, name='user_profile'),
]

In your views.py you have to adjust your view to receive the URL argument:

from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404

def profile(request, username):
    # do whatever you want,
    # maybe getting the user for the provided username and pass it to the template
    user = get_object_or_404(get_user_model(), username=username)
    return render(request, 'profile.html', {'user': user})

The templates may contain the URL to any profile, which is generated with the {% url 'name' arguments %} template tag.

This is the profile of
<a href="{% url 'user_profile' username=user.username %}">
  {{ user.username }}
</a>
Sign up to request clarification or add additional context in comments.

3 Comments

i can't use the "get_user_model()" or "get_object_or_404()" method cause its a custom authentication and user model made by me not the default user library that comes with django
Well, you can just change to code to fit your needs. The general idea should fit anyway.
You should set AUTH_USER_MODEL in your settings file (if you have customized it as you said). If you set it before then you can use get_user_model or other helper methods with it.
0

In your URL conf:

path('profile/<str:username>/', profile)

Don't forget to add the username wherever the link is displayed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.