[Answered ]-Django: how to generate random number inside a slug field

1👍

StackOverflow does not use a "random number". It simply uses the primary key. Indeed, you can browse to a post where the number is a decrement (or increment) of that number, and that will (often) show a post as well.

You thus can define a view with:

path(
    'question/<int:pk>/<slug:slug>/', views.some_views_name, name='Redirect-name'
)

In your model you can pass the primary key:

class Product(models.Model):
    # …

    def get_user_public_url(self):
        return reverse(
            'Public-Profile',
            kwargs={'pk': self.pk, 'slug': self.user.profile.slug},
        )

Class-based views, like a DetailView will automatically filter on a primary key, if it can find one. For a function-based view, you can work with:

from django.shortcuts import get_object_or_404


def some_view_name(request, pk, slug):
    product = get_object_or_404(Product, pk=pk, slug=slug)
    # …

Note: You can make use of django-autoslug [GitHub] to automatically create a slug based on other field(s).


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Leave a comment