Reputation: 197
I want to show the username or name of the person I want to update details for, in the url of update view. The only method I know is to display pk in the url. Is there a method to replace pk with a field value? Thanks in advance.
Upvotes: 1
Views: 1010
Reputation: 7330
you can use slug
for this.You can install slug using pip install django-autoslug
For example:
from autoslug import AutoSlugField
class A(models.Model):
field = models.CharField(max_length=250)
slug = AutoSlugField(unique_with='id', populate_from='field')
In urls.py
use slug like this:
path('<slug>/..../', views...., name='....'),
Upvotes: 2
Reputation: 476659
Yes, you can simply define a slug
or str
part in the url. For example:
# app/urls.py
from django.urls import path
from app import views
urlpatterns = [
path('user/<str:username>/', views.user_details),
]
and in your view, you can for example query with the username
field is the username
URL parameter:
# app/views.py
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
def user_details(request, username):
user = get_object_or_404(User, username=username)
# ...
Upvotes: 2