0

I'm getting the error because I have two first-rant slug's on the database. I expected this to come. I have a solution in mind to add random numbers at the end of the url. Can anyone help me implement this using the RandomCharField of https://django-extensions.readthedocs.io/en/latest/field_extensions.html.

Here are my models:

class Category(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Category, self).save(*args, **kwargs)
        return self.slug

    def get_context_data(self, **kwargs):
        context = super(self).get_context_data(**kwargs)
        context['rants'] = Rant.objects.filter('category')
        return 


class Rant(models.Model):
    title = models.CharField(max_length=150)
    slug = models.SlugField(max_length=150)
    categories = models.ManyToManyField(
        Category, related_name='rants_categories')
    user = models.ForeignKey(User, default='', null=True, related_name='users_rant', on_delete=models.PROTECT)
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateField(auto_now=True)

    class Meta:
        verbose_name = "rant"
        verbose_name_plural = 'rants'

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Rant, self).save(*args, **kwargs)
        return self.slug

    def get_absolute_url(self):
        from django.urls import reverse
        return reverse('main:detail', kwargs={'slug': self.slug})

Here are my views:

class RantListView(ListView):
    model = Rant
    template_name = 'rants/list.html'
    context_object_name = 'rants'


class RantDetailView(DetailView):
    model = Rant
    template_name = 'rants/detail.html'


def rant_category(request, slug):
    rants = Rant.objects.filter(
        categories__slug__contains=slug
    )
    context = {
        "slug": slug,
        "rants": rants
    }
    return render(request, "rants/category_list.html", context)

And finally my urls

    path('', RantListView.as_view(), name='list'),
    path('<slug:slug>/', RantDetailView.as_view(), name='detail'),
    path('category/<slug:slug>/', rant_category, name='categories'),

My expected output is to have a <slug:slug>/<random_chars>/ at the end of the url

1
  • 1
    the clean way would be to add a date or random chars to the slug directly to make slug unique. Otherwise you need to store random chars in your model and change the standard behavior of ListView and DetailView.
    – Razenstein
    Apr 14 at 8:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.