用两个子段反转一个URL

时间:2018-10-16 11:35:18

标签: python django django-views django-urls

我试图理解一个基本示例,该示例添加了2个相关类的类别和详细信息。

/categories URL有效,但是我无法使/categories/detail有效。我收到以下错误:

Reverse for 'categorydetail' with arguments '('onedetailfromcategory',)' not found. 1 pattern(s) tried: ['(?P<cat_slug>[^/]+)/(?P<det_slug>[^/]+)$']

这是我的文件:

#Models:

class Categories(models.Model):
    name = models.CharField(max_length=50,unique=True)
    cat_slug = models.SlugField(max_length=100,unique=True)

    def __str__(self):
        return self.name

class Details(models.Model):
    title = models.CharField(max_length=100)
    det_slug= models.SlugField(max_length=100,unique=True)

    categorie = models.ForeignKey('Categories', on_delete=models.CASCADE,  related_name="Categories")


    def __str__(self):
        return self.title


#Views:         
class ListCategorie(DetailView):
    model = Categories
    slug_field = 'cat_slug'
    context_object_name = "listcategories"
    template_name = "show/categories.html"

class DetailCategorie(DetailView):
    model = Details
    slug_field = 'det_slug'
    context_object_name = "categorydetail"
    template_name = "show/detail.html"

#Urls:
    path('<cat_slug>', views.ListCategorie.as_view(), name='listcategories'),
    path('<cat_slug>/<det_slug>', views.DetailCategorie.as_view(), name='categorydetail'),

#Categories.html

{% for x in listcategories.Categories.all %}
<p> {{x.title}} </p>
<li><a href="{% url 'categorydetail' x.det_slug %}">URL</a></li>
{% endfor %}

1 个答案:

答案 0 :(得分:1)

您的网址格式为

path('<cat_slug>/<det_slug>', views.DetailCategorie.as_view(), name='categorydetail'),

因此,在反转URL时,您需要提供cat_slugdet_slug

{% url 'categorydetail' x.categorie.cat_slug x.det_slug %}