-1

I am trying to understand a basic example of adding both categories and detail slugs from 2 related classes.

The /categories URL works, but I can't make /categories/detail work. I get the following error:

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

Here are my files:

#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 %}
Alasdair
  • 298,606
  • 55
  • 578
  • 516
michltm
  • 1,399
  • 2
  • 13
  • 33
  • Did you checked this https://stackoverflow.com/questions/15080083/django-url-slug-for-detail-page ? – Umair Mohammad Oct 16 '18 at 11:43
  • "is not working" is a totally useless description of a problem. – bruno desthuilliers Oct 16 '18 at 11:53
  • Fair enough. Edited. – michltm Oct 16 '18 at 12:10
  • Using `related_name="Categories"` is very confusing. You use it to get the related details for a category, therefore `related_name='details'` and `{% for detail in listcategories.details.all %}` would be much clearer. – Alasdair Oct 16 '18 at 12:23
  • Note that the recommendation in Django is to use singular for model names, e.g. `Categorie` and `Detail` instead of `Categories` and `Details`. I would also use `slug` instead of `cat_slug` and `det_slug`. Your code will usually be something like `categorie.slug` or `detail.slug`, so it's clear what sort of slug it is without the prefix in the fieldname. – Alasdair Oct 16 '18 at 12:25
  • Ok got it. Thank you for detailing the good practices. – michltm Oct 16 '18 at 12:32

1 Answers1

1

Your URL pattern is

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

Therefore you need to provide cat_slug and det_slug when reversing the URL:

{% url 'categorydetail' x.categorie.cat_slug x.det_slug %}
Alasdair
  • 298,606
  • 55
  • 578
  • 516