Search code examples
djangourlslug

How to get slugs from different models in the urls i.e path(<slug:slug1>/<slug:slug2>/)?


Im trying to get a ur pattern that looks like this WWW.domain.com/slug1/slug2, where slug1 is the foreignkey to slug to. Think of it like library.com//. The author and book are two different models, both with their own slug. Is there a way where i can import the slug from author to the detailview of the book and then use it in the urls for the book detailview?

This is how i imagine the path to look like:

    path('brands/<slug:brand_slug>/<slug:model_slug>', views.Brand_ModelsDetailView.as_view(), name='model-detail'),

These are my models:

class Brand(models.Model):
    brand_name = models.CharField(
        max_length=50, help_text='Enter the brand name',)  
    slug = AutoSlugField(populate_from='brand_name', default = "slug_error", unique = True, always_update = True,)


    def get_absolute_url(self):
        """Returns the url to access a particular brand instance."""
        return reverse('brand-detail', kwargs={'slug':self.slug})

    def __str__(self):
        return self.brand_name

class Brand_Models(models.Model):
    name = models.CharField(max_length=100)
    brand = models.ForeignKey('Brand', on_delete=models.SET_NULL, null=True)
    slug = AutoSlugField(populate_from='name', default = "slug_error_model", unique = True, always_update = True,)


    def get_absolute_url(self):
        """Returns the url to access a particular founder instance."""
        return reverse('model-detail', kwargs={'slug':self.slug})

    def __str__(self):
        return self.name

My current attempt at the views:

class Brand_ModelsDetailView(generic.DetailView):
    model = Brand_Models


    def get_queryset(self):
        qs = super(Brand_ModelsDetailView, self).get_queryset()
        return qs.filter(
            brand__slug=self.kwargs['brand_slug'],
            slug=self.kwargs['model_slug']
        )

EDIT:

class RefrenceDetailView(generic.DetailView):
   model = Refrence

   def get_queryset(self):
       qs = super(RefrenceDetailView, self).get_queryset()
       return qs.filter(
            brand__slug=self.kwargs['brand_slug'],
            model__slug=self.kwargs['model_slug'],
        slug = self.kwargs['ref_slug']
    )

Solution

  • Your error is just with the get_absolute_url method of Brand_Models; because the detail URL takes two slugs, you need pass them both to reverse there.

    return reverse('model-detail', kwargs={'brand_slug': self.brand.slug, 'model_slug':self.slug})