Skip to content

Instantly share code, notes, and snippets.

@KabakiAntony
Last active February 7, 2023 01:36
Show Gist options
  • Select an option

  • Save KabakiAntony/043bc22f8330e3beefffcbdd314e91ca to your computer and use it in GitHub Desktop.

Select an option

Save KabakiAntony/043bc22f8330e3beefffcbdd314e91ca to your computer and use it in GitHub Desktop.
product model definition
import secrets
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
class Product(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(unique=True, blank=True)
description = models.TextField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("products:product_detail", kwargs={"slug": self.slug})
def save(self, *args, **kwargs):
if not self.slug:
random_url = secrets.token_hex(8)
joined_string = "-".join([self.title,random_url])
self.slug = slugify(joined_string)
super(Product, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = "Products"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment