Home > front end >  how to pass data from a model to the url in django?
how to pass data from a model to the url in django?

Time:07-11

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?

CodePudding user response:

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>

CodePudding user response:

In your URL conf:

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

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

  • Related