Last active
February 7, 2023 01:36
-
-
Save KabakiAntony/043bc22f8330e3beefffcbdd314e91ca to your computer and use it in GitHub Desktop.
product model definition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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