简体   繁体   English

如何在网址中使用字段值而不是pk?

[英]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. 我知道的唯一方法是在网址中显示pk。 Is there a method to replace pk with a field value? 有没有一种方法可以用字段值替换pk? Thanks in advance. 提前致谢。

Yes, you can simply define a slug or str part in the url. 是的,您只需在URL中定义一个slugstr部分。 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: 并且在您的视图中,您可以例如使用username字段是username URL参数进行查询:

# 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)
    # ...

you can use slug for this.You can install slug using pip install django-autoslug For example: 您可以为此使用slug 。您可以使用pip install django-autoslug安装slug例如:

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: urls.py使用slug,如下所示:

path('<slug>/..../', views...., name='....'),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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