简体   繁体   中英

How to use a field value instead of pk in the url?

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.

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/', 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):
    user = get_object_or_404(User)
    # ...

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='....'),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM