gpt4 book ai didi

django - 如何在详细 View 中用 slug 替换 pk

转载 作者:行者123 更新时间:2023-12-05 05:01:27 33 4
gpt4 key购买 nike

如何让slug放置pk?

View .py

from django.shortcuts import render
from django.views.generic import ListView, DetailView

from .models import Category,Subcategory, Product, Characteristic

class CategoryView(ListView):
"""list of categories"""
model = Category


class CategoryDetailView(DetailView):
"""Full description of categories"""
model = Category

模型.py

class Category(models.Model):
name_category = models.CharField(verbose_name = 'name category', max_length = 100, null=True)
image = models.ImageField(null=True, blank=True, upload_to="media/", verbose_name='pic')

def __str__(self):
return self.name_category


class Subcategory(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='category', related_name='sub')
name_subcategory = models.CharField(verbose_name = 'name subcategory', max_length = 100, null=True)
image = models.ImageField(null=True, blank=True, upload_to="media/", verbose_name='pic')
url = models.SlugField(max_length=160, unique=True, null=True)

def __str__(self):
return self.name_subcategory

网址.py

urlpatterns = [
path("", views.CategoryView.as_view()),
path('<int:pk>/', views.CategoryDetailView.as_view(), name='category_detail'),
]

在我这样形成的链接模板中

{% for category in category_list %}
<a href="{% url 'category_detail' pk=category.pk %}">{{category.name_category}}</a>
<img src="{{category.image.url}}" width="100px" height="100px">
{% for img in category.sub.all %}
{{ img.name_subcategory }}
{% endfor %}
{% endfor %}

现在我的链接是这样构成的 http://127.0.0.1:8000/1/如何使链接中的位置 pk 替换为子类别模型中的 slug

最佳答案

在您的模型中,您需要一个 SlugField。使用 AutoSlugField [readthedocs] 可能很容易django-autoslug package [readthedocs] :

from autoslug import AutoSlugField

class Category(models.Model):
name_category = models.CharField(
verbose_name='name category',
max_length=100,
null=True
)
image = models.ImageField(
null=True,
blank=True,
upload_to='media/',
verbose_name='pic'
)
slug = AutoSlugField(populate_from='name_category')

def __str__(self):
return self.name_category

在 url 模式中,您使用名为 slug 的参数:

urlpatterns = [
path('', views.CategoryView.as_view()),
path('<b><slug:slug></b>/', views.CategoryDetailView.as_view(), name='category_detail'),
]

然后在模板中使用 slug 字段代替主键:

{% for category in category_list %}
<a href="<b>{% url 'category_detail' slug=category.slug %}</b>">{{category.name_category}}</a>
<img src="{{category.image.url}}" width="100px" height="100px">
{% for img in category.sub.all %}
{{ img.name_subcategory }}
{% endfor %}
{% endfor %}

关于django - 如何在详细 View 中用 slug 替换 pk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62693949/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com