Snippets Collections
// models.py
class Product(models.Model):
    title = models.CharField(max_length=225, unique=True)
    slug = models.SlugField(max_length=225, unique=True, null=True)

// admin.py
class ProductAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('title',)}

// views.py
class productDetail(generic.DetailView):
    model = Detail
    template_name = 'detail.html'

// urls.py
    path('product/<slug:slug>/', views.productDetail.as_view(), name='productDetail'),
// models.py
from django.db.models.fields import FloatField

class Product(models.Model):
    title = models.CharField(max_length=225)
    price = models.FloatField()
    discount_percent = FloatField(default=0) # Assigning it a default value of 0 so it doesn't throw a 'NoneType' error when it's null.
  
    @property
    def discount(self):
        if self.discount_percent > 0:
            discounted_price = self.price - self.price * self.discount_percent / 100
            return discounted_price

class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
	
	# get_total function has to be updated too to calculate using the correct current price
    @property
    def get_total(self):
        if self.product.discount_percent > 0:
            price_now = self.product.price - self.product.price * self.product.discount_percent / 100
        else:
            price_now = self.product.price

        total = price_now * self.quantity
        return total

// Your template
{% if product.discount_percent %}
                <h4 class="product__price--original">₾{{ product.price|floatformat:2 }}</h4>
                <h4 class="product__price--discounted">₾{{ product.discount|floatformat:2 }}</h4>
                {% else %}  
                <h4>₾{{ product.price|floatformat:2 }}</h4>
                {% endif %}
                
// Here's some Sass too, if you need it
.product__price {
  &--original {
    text-decoration: line-through;
  }
  &--discounted {
    color: green;
  }
}
// models.py
from django.utils import timezone

class Product(models.Model):
    name = models.CharField(max_length=225)
    created_on = models.DateTimeField(auto_now_add=True)
    
    @property
    def is_new(self):
        now = timezone.now()
        diff = now - self.created_on
        
        if diff.days < 7: # 7 is the number of days
            return True
        else:
            return False  

// in your template
<h4>{{ product.name }}{% if product.is_new %}<span>სიახლე</span>{% endif %}</h4>
star

Mon Oct 11 2021 04:11:32 GMT+0000 (Coordinated Universal Time)

#django #ecommerce #slug
star

Sat Oct 09 2021 22:08:37 GMT+0000 (Coordinated Universal Time)

#django #ecommerce

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension