feat: cart

This commit is contained in:
2024-11-27 17:07:03 +01:00
parent f1b25b1fdf
commit fa1d904db5
15 changed files with 448 additions and 109 deletions
+90
View File
@@ -0,0 +1,90 @@
# Generated by Django 5.1.3 on 2024-11-27 12:10
import django.db.models.deletion
import uuid
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("shop", "0005_productprice_price_with_tax"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="Cart",
fields=[
(
"uuid",
models.UUIDField(
default=uuid.uuid4,
primary_key=True,
serialize=False,
verbose_name="uuid",
),
),
(
"creation_date",
models.DateTimeField(
auto_now_add=True, verbose_name="fecha de creación"
),
),
(
"user",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
verbose_name="usuario",
),
),
],
options={
"verbose_name": "carrito",
"verbose_name_plural": "carritos",
},
),
migrations.CreateModel(
name="CartItem",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"quantity",
models.PositiveIntegerField(default=1, verbose_name="cantidad"),
),
(
"cart",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="items",
to="shop.cart",
verbose_name="carrito",
),
),
(
"product",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="shop.product",
verbose_name="producto",
),
),
],
options={
"verbose_name": "línea de carrito",
"verbose_name_plural": "líneas de carrito",
},
),
]
+39
View File
@@ -6,6 +6,10 @@ from django.utils import timezone
from django.utils.text import gettext_lazy as _ from django.utils.text import gettext_lazy as _
from django.utils.text import slugify from django.utils.text import slugify
from django.contrib.auth import get_user_model
User = get_user_model()
class TimestampedModel(models.Model): class TimestampedModel(models.Model):
creation_date = models.DateTimeField( creation_date = models.DateTimeField(
@@ -398,3 +402,38 @@ class Order(TimestampedModel):
class Meta: class Meta:
verbose_name = _("pedido") verbose_name = _("pedido")
verbose_name_plural = _("pedidos") verbose_name_plural = _("pedidos")
class Cart(models.Model):
uuid = models.UUIDField(default=uuid4, primary_key=True, verbose_name=_("uuid"))
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
verbose_name=_("usuario"),
blank=True,
null=True,
)
creation_date = models.DateTimeField(
auto_now_add=True, verbose_name=_("fecha de creación")
)
class Meta:
verbose_name = _("carrito")
verbose_name_plural = _("carritos")
class CartItem(models.Model):
cart = models.ForeignKey(
"shop.Cart",
on_delete=models.CASCADE,
related_name="items",
verbose_name=_("carrito"),
)
product = models.ForeignKey(
"shop.Product", on_delete=models.CASCADE, verbose_name=_("producto")
)
quantity = models.PositiveIntegerField(default=1, verbose_name=_("cantidad"))
class Meta:
verbose_name = _("línea de carrito")
verbose_name_plural = _("líneas de carrito")
View File
+35
View File
@@ -0,0 +1,35 @@
from django.views.generic import TemplateView
from shop.filters import ProductFilter
from shop.models import Product
from web.mixins import FilteredQuerysetMixin, PaginatedQuerysetMixin, CartMixin
class ListProducts(TemplateView, FilteredQuerysetMixin, PaginatedQuerysetMixin):
template_name = "web/list_products.html"
queryset = Product.objects.all()
filter_class = ProductFilter
def get_context_data(self, **kwargs):
qs = self.get_queryset()
page = self.get_paginated_queryset(qs)
return {
"page": page,
"has_next_page": page.has_next(),
"has_previous_page": page.has_previous(),
}
class CartDropdown(TemplateView, CartMixin):
template_name = "components/cart/cart_navbar.html"
def get_context_data(self, **kwargs):
cart = self.get_cart()
return {
"cart": cart,
}
list_products = ListProducts.as_view()
cart_dropdown = CartDropdown.as_view()
+13
View File
@@ -0,0 +1,13 @@
from django import forms
from django.forms import widgets
class CartItemForm(forms.Form):
"""
<input type="hidden" name="product" value="{{ product.pk }}">
<label for="quantity">{% translate 'Cantidad' %}</label>
<input id="quantity" type="number" name="quantity" value="1">
"""
product = forms.IntegerField(widget=widgets.HiddenInput)
quantity = forms.IntegerField()
+13
View File
@@ -1,6 +1,9 @@
from django.conf import settings from django.conf import settings
from django.core.paginator import Paginator from django.core.paginator import Paginator
from shop.models import Cart
from web.settings import ANONYMOUS_CART_ID_COOKIE_NAME
class FilteredQuerysetMixin: class FilteredQuerysetMixin:
queryset = None queryset = None
@@ -25,3 +28,13 @@ class PaginatedQuerysetMixin:
page = self.request.GET.get("page", 1) page = self.request.GET.get("page", 1)
qs = paginator.get_page(page) qs = paginator.get_page(page)
return qs return qs
class CartMixin:
def get_cart(self):
if not self.request.user.is_authenticated:
uid = self.request.COOKIES.get(ANONYMOUS_CART_ID_COOKIE_NAME)
cart = Cart.objects.get(uuid=uid)
else:
cart = Cart.objects.filter(user=self.request.user).first()
return cart
+1
View File
@@ -0,0 +1 @@
ANONYMOUS_CART_ID_COOKIE_NAME = "caid"
@@ -0,0 +1,15 @@
{% load i18n %}
<form action="" hx-post="{% url 'web:add_cart_item' %}" hx-swap="none">
{% csrf_token %}
<input type="hidden" name="product" value="{{ product.pk }}">
<input id="quantity" type="hidden" name="quantity" value="1">
<button
class="inline-flex items-center rounded-lg bg-primary-700 px-5 py-2.5 text-sm font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4 focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">
<svg class="-ms-2 me-2 h-5 w-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24"
height="24" fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 4h1.5L8 16m0 0h8m-8 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm8 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm.75-3H7.5M11 7H6.312M17 4v6m-3-3h6"/>
</svg>
{% translate 'Añadir al carrito' %}
</button>
</form>
@@ -1,35 +1,57 @@
{% load i18n %} {% load i18n %}
<div class="grid grid-cols-2"> <div class="grid grid-cols-2">
<div>
<a href="#" class="truncate text-sm font-semibold leading-none text-gray-900 dark:text-white hover:underline">Apple iPhone 15</a>
<p class="mt-0.5 truncate text-sm font-normal text-gray-500 dark:text-gray-400">$599</p>
</div>
<div class="flex items-center justify-end gap-6"> {% if cart.items.count == 0 %}
<p class="text-sm font-normal leading-none text-gray-500 dark:text-gray-400">Qty: 1</p> <h2 class="text-sm font-medium text-gray-900 dark:text-white">No hay nada en el carrito</h2>
{% endif %}
<button data-tooltip-target="tooltipRemoveItem1a" type="button" {% for cart_item in cart.items.all %}
class="text-red-600 hover:text-red-700 dark:text-red-500 dark:hover:text-red-600"> <div>
<span class="sr-only"> Remove </span> <a href="#"
<svg class="h-4 w-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="truncate text-sm font-semibold leading-none text-gray-900 dark:text-white hover:underline">{{ cart_item.product.name }}</a>
viewBox="0 0 24 24"> <p
<path fill-rule="evenodd" class="mt-0.5 truncate text-sm font-normal text-gray-500 dark:text-gray-400">{{ cart_item.product.price.price_with_tax }}</p>
d="M2 12a10 10 0 1 1 20 0 10 10 0 0 1-20 0Zm7.7-3.7a1 1 0 0 0-1.4 1.4l2.3 2.3-2.3 2.3a1 1 0 1 0 1.4 1.4l2.3-2.3 2.3 2.3a1 1 0 0 0 1.4-1.4L13.4 12l2.3-2.3a1 1 0 0 0-1.4-1.4L12 10.6 9.7 8.3Z"
clip-rule="evenodd"/>
</svg>
</button>
<div id="tooltipRemoveItem1a" role="tooltip"
class="tooltip invisible absolute z-10 inline-block rounded-lg bg-gray-900 px-3 py-2 text-sm font-medium text-white opacity-0 shadow-sm transition-opacity duration-300 dark:bg-gray-700">
Remove item
<div class="tooltip-arrow" data-popper-arrow></div>
</div> </div>
</div>
<div class="flex items-center justify-end gap-6">
<p
class="text-sm font-normal leading-none text-gray-500 dark:text-gray-400">{% translate 'Cantidad' %}: {{ cart_item.quantity }}</p>
<form hx-post="{% url 'web:delete_cart_item' pk=cart_item.pk %}"
hx-swap="none">
<button data-tooltip-target="tooltipRemoveItem1a" type="submit"
class="text-red-600 hover:text-red-700 dark:text-red-500 dark:hover:text-red-600"
>
{% csrf_token %}
<span class="sr-only">{% translate 'Quitar' %}</span>
<svg class="h-4 w-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor"
viewBox="0 0 24 24">
<path fill-rule="evenodd"
d="M2 12a10 10 0 1 1 20 0 10 10 0 0 1-20 0Zm7.7-3.7a1 1 0 0 0-1.4 1.4l2.3 2.3-2.3 2.3a1 1 0 1 0 1.4 1.4l2.3-2.3 2.3 2.3a1 1 0 0 0 1.4-1.4L13.4 12l2.3-2.3a1 1 0 0 0-1.4-1.4L12 10.6 9.7 8.3Z"
clip-rule="evenodd"/>
</svg>
</button>
</form>
<div id="tooltipRemoveItem1a" role="tooltip"
class="tooltip invisible absolute z-10 inline-block rounded-lg bg-gray-900 px-3 py-2 text-sm font-medium text-white opacity-0 shadow-sm transition-opacity duration-300 dark:bg-gray-700"
>
Remove item
<div class="tooltip-arrow" data-popper-arrow></div>
</div>
</div>
{% endfor %}
</div> </div>
<a href="#" title="" {% if cart.items.count > 0 %}
class="mb-2 me-2 inline-flex w-full items-center justify-center rounded-lg bg-primary-700 px-5 py-2.5 text-sm <a href="#" title=""
class="mb-2 me-2 inline-flex w-full items-center justify-center rounded-lg bg-primary-700 px-5 py-2.5 text-sm
font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4 focus:ring-primary-300 font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4 focus:ring-primary-300
dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800" dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800"
role="button"> {% translate 'Ir a pagar' %} role="button"> {% translate 'Ir a pagar' %}
</a> </a>
{% endif %}
@@ -0,0 +1,87 @@
{% load i18n %}
<button
hx-on:click="htmx.toggleClass(htmx.find('#myCartDropdown1'), 'hidden'); htmx.addClass(htmx.find('#userDropdown1'), 'hidden')"
id="myCartDropdownButton1"
data-dropdown-toggle="myCartDropdown1" type="button"
class="inline-flex items-center rounded-lg justify-center p-2 hover:bg-gray-100 dark:hover:bg-gray-700 text-sm font-medium leading-none text-gray-900 dark:text-white">
<span class="sr-only">
{% blocktranslate %}
Carrito
{% endblocktranslate %}({{ cart.items.count }})
</span>
<svg class="w-5 h-5 lg:me-1" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24"
fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M5 4h1.5L9 16m0 0h8m-8 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm8 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm-8.5-3h9.25L19 7H7.312"/>
</svg>
<span class="sm:flex">
{% blocktranslate %}
Carrito
{% endblocktranslate %}({{ cart.items.count }})</span>
<svg class="hidden sm:flex w-4 h-4 text-gray-900 dark:text-white ms-1" aria-hidden="true"
xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="m19 9-7 7-7-7"/>
</svg>
</button>
<!-- Cart -->
<div id="myCartDropdown1"
class="absolute top-10 hidden z-10 mx-auto max-w-sm space-y-4 overflow-hidden rounded-lg bg-white p-4 antialiased shadow-lg dark:bg-gray-800">
<div class="grid grid-cols-2">
{% if cart.items.count == 0 %}
<h2 class="text-sm font-medium text-gray-900 dark:text-white">No hay nada en el carrito</h2>
{% endif %}
{% for cart_item in cart.items.all %}
<div>
<a href="#"
class="truncate text-sm font-semibold leading-none text-gray-900 dark:text-white hover:underline">{{ cart_item.product.name }}</a>
<p
class="mt-0.5 truncate text-sm font-normal text-gray-500 dark:text-gray-400">{{ cart_item.product.price.price_with_tax }}</p>
</div>
<div class="flex items-center justify-end gap-6">
<p
class="text-sm font-normal leading-none text-gray-500 dark:text-gray-400">{% translate 'Cantidad' %}: {{ cart_item.quantity }}</p>
<form hx-post="{% url 'web:delete_cart_item' pk=cart_item.pk %}"
hx-swap="none">
<button data-tooltip-target="tooltipRemoveItem1a" type="submit"
class="text-red-600 hover:text-red-700 dark:text-red-500 dark:hover:text-red-600"
>
{% csrf_token %}
<span class="sr-only">{% translate 'Quitar' %}</span>
<svg class="h-4 w-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor"
viewBox="0 0 24 24">
<path fill-rule="evenodd"
d="M2 12a10 10 0 1 1 20 0 10 10 0 0 1-20 0Zm7.7-3.7a1 1 0 0 0-1.4 1.4l2.3 2.3-2.3 2.3a1 1 0 1 0 1.4 1.4l2.3-2.3 2.3 2.3a1 1 0 0 0 1.4-1.4L13.4 12l2.3-2.3a1 1 0 0 0-1.4-1.4L12 10.6 9.7 8.3Z"
clip-rule="evenodd"/>
</svg>
</button>
</form>
<div id="tooltipRemoveItem1a" role="tooltip"
class="tooltip invisible absolute z-10 inline-block rounded-lg bg-gray-900 px-3 py-2 text-sm font-medium text-white opacity-0 shadow-sm transition-opacity duration-300 dark:bg-gray-700"
>
Remove item
<div class="tooltip-arrow" data-popper-arrow></div>
</div>
</div>
{% endfor %}
</div>
{% if cart.items.count > 0 %}
<a href="#" title=""
class="mb-2 me-2 inline-flex w-full items-center justify-center rounded-lg bg-primary-700 px-5 py-2.5 text-sm
font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4 focus:ring-primary-300
dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800"
role="button"> {% translate 'Ir a pagar' %}
</a>
{% endif %}
</div>
+39 -53
View File
@@ -46,58 +46,38 @@
{% include 'components/theme-switch.html' %} {% include 'components/theme-switch.html' %}
<!-- Show/Hide cart --> <!-- Show/Hide cart -->
<button hx-on:click="htmx.toggleClass(htmx.find('#myCartDropdown1'), 'hidden'); htmx.addClass(htmx.find('#userDropdown1'), 'hidden')" <div id="navbar-cart-dropdown" hx-get="{% url 'web:cart_dropdown' %}" hx-trigger="load"></div>
id="myCartDropdownButton1"
data-dropdown-toggle="myCartDropdown1" type="button"
class="inline-flex items-center rounded-lg justify-center p-2 hover:bg-gray-100 dark:hover:bg-gray-700 text-sm font-medium leading-none text-gray-900 dark:text-white">
<span class="sr-only">
{% translate 'Carrito' %}
</span>
<svg class="w-5 h-5 lg:me-1" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24"
fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M5 4h1.5L9 16m0 0h8m-8 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm8 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm-8.5-3h9.25L19 7H7.312"/>
</svg>
<span class="sm:flex">{% translate 'Carrito' %}</span>
<svg class="hidden sm:flex w-4 h-4 text-gray-900 dark:text-white ms-1" aria-hidden="true"
xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="m19 9-7 7-7-7"/>
</svg>
</button>
<!-- Cart -->
<div id="myCartDropdown1"
class="absolute top-10 hidden z-10 mx-auto max-w-sm space-y-4 overflow-hidden rounded-lg bg-white p-4 antialiased shadow-lg dark:bg-gray-800">
{% include 'components/cart/cart_dropdown.html' %}
</div>
{% if request.user.is_authenticated %} {% if request.user.is_authenticated %}
<!-- Show/Hide user account dropdown --> <!-- Show/Hide user account dropdown -->
<button hx-on:click="htmx.toggleClass(htmx.find('#userDropdown1'), 'hidden'); htmx.addClass(htmx.find('#myCartDropdown1'), 'hidden')" <button
id="userDropdownButton1" hx-on:click="htmx.toggleClass(htmx.find('#userDropdown1'), 'hidden'); htmx.addClass(htmx.find('#myCartDropdown1'), 'hidden')"
data-dropdown-toggle="userDropdown1" type="button" id="userDropdownButton1"
class="inline-flex items-center rounded-lg justify-center p-2 hover:bg-gray-100 dark:hover:bg-gray-700 text-sm font-medium leading-none text-gray-900 dark:text-white"> data-dropdown-toggle="userDropdown1" type="button"
<svg class="w-5 h-5 me-1" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" class="inline-flex items-center rounded-lg justify-center p-2 hover:bg-gray-100 dark:hover:bg-gray-700 text-sm font-medium leading-none text-gray-900 dark:text-white">
fill="none" viewBox="0 0 24 24"> <svg class="w-5 h-5 me-1" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24"
<path stroke="currentColor" stroke-width="2" fill="none" viewBox="0 0 24 24">
d="M7 17v1a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1v-1a3 3 0 0 0-3-3h-4a3 3 0 0 0-3 3Zm8-9a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/> <path stroke="currentColor" stroke-width="2"
</svg> d="M7 17v1a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1v-1a3 3 0 0 0-3-3h-4a3 3 0 0 0-3 3Zm8-9a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/>
</svg>
{% translate 'Mi cuenta' %} {% translate 'Mi cuenta' %}
<svg class="w-4 h-4 text-gray-900 dark:text-white ms-1" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" <svg class="w-4 h-4 text-gray-900 dark:text-white ms-1" aria-hidden="true"
width="24" height="24" fill="none" viewBox="0 0 24 24"> xmlns="http://www.w3.org/2000/svg"
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" width="24" height="24" fill="none" viewBox="0 0 24 24">
d="m19 9-7 7-7-7"/> <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
</svg> d="m19 9-7 7-7-7"/>
</button> </svg>
</button>
<!-- User account dropdown --> <!-- User account dropdown -->
<div id="userDropdown1" <div id="userDropdown1"
class="absolute top-10 hidden z-10 w-56 divide-y divide-gray-100 overflow-hidden overflow-y-auto rounded-lg bg-white antialiased shadow dark:divide-gray-600 dark:bg-gray-700 right-0"> class="absolute top-10 hidden z-10 w-56 divide-y divide-gray-100 overflow-hidden overflow-y-auto rounded-lg bg-white antialiased shadow dark:divide-gray-600 dark:bg-gray-700 right-0">
{% include 'components/users/user_dropdown.html' %} {% include 'components/users/user_dropdown.html' %}
</div> </div>
{% else %} {% else %}
<a href="{% url 'users:login' %}" class="inline-flex items-center rounded-lg justify-center p-2 hover:bg-gray-100 dark:hover:bg-gray-700 text-sm font-medium leading-none text-gray-900 dark:text-white">Inicia sesión</a> <a href="{% url 'users:login' %}"
class="inline-flex items-center rounded-lg justify-center p-2 hover:bg-gray-100 dark:hover:bg-gray-700 text-sm font-medium leading-none text-gray-900 dark:text-white">Inicia
sesión</a>
{% endif %} {% endif %}
<!-- Show/Hide menu items --> <!-- Show/Hide menu items -->
<button hx-on:click="htmx.toggleClass(htmx.find('#ecommerce-navbar-menu-1'), 'hidden')" type="button" <button hx-on:click="htmx.toggleClass(htmx.find('#ecommerce-navbar-menu-1'), 'hidden')" type="button"
@@ -119,22 +99,28 @@
class="bg-gray-50 dark:bg-gray-700 dark:border-gray-600 border border-gray-200 rounded-lg py-3 hidden px-4 mt-4"> class="bg-gray-50 dark:bg-gray-700 dark:border-gray-600 border border-gray-200 rounded-lg py-3 hidden px-4 mt-4">
<ul class="text-gray-900 dark:text-white text-sm font-medium dark:text-white space-y-3"> <ul class="text-gray-900 dark:text-white text-sm font-medium dark:text-white space-y-3">
<li> <li>
<a href="{% url 'web:index' %}" class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Inicio' %}</a> <a href="{% url 'web:index' %}"
class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Inicio' %}</a>
</li> </li>
<li> <li>
<a href="{% url 'web:index' %}" class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Más vendidos' %}</a> <a href="{% url 'web:index' %}"
class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Más vendidos' %}</a>
</li> </li>
<li> <li>
<a href="{% url 'web:index' %}" class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Ideas de regalo' %}</a> <a href="{% url 'web:index' %}"
class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Ideas de regalo' %}</a>
</li> </li>
<li> <li>
<a href="{% url 'web:index' %}" class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Juegos' %}</a> <a href="{% url 'web:index' %}"
class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Juegos' %}</a>
</li> </li>
<li> <li>
<a href="{% url 'web:index' %}" class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Electrónica' %}</a> <a href="{% url 'web:index' %}"
class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Electrónica' %}</a>
</li> </li>
<li> <li>
<a href="{% url 'web:index' %}" class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Ofertas del día' %}</a> <a href="{% url 'web:index' %}"
class="hover:text-primary-700 dark:hover:text-primary-500">{% translate 'Ofertas del día' %}</a>
</li> </li>
</ul> </ul>
</div> </div>
+1 -9
View File
@@ -55,15 +55,7 @@
<p <p
class="text-2xl font-extrabold leading-tight text-gray-900 dark:text-white">{{ product.price.price_with_tax }}€</p> class="text-2xl font-extrabold leading-tight text-gray-900 dark:text-white">{{ product.price.price_with_tax }}€</p>
<button type="button" {% include 'components/cart/add_to_cart.html' %}
class="inline-flex items-center rounded-lg bg-primary-700 px-5 py-2.5 text-sm font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4 focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">
<svg class="-ms-2 me-2 h-5 w-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24"
height="24" fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 4h1.5L8 16m0 0h8m-8 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm8 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm.75-3H7.5M11 7H6.312M17 4v6m-3-3h6"/>
</svg>
{% translate 'Añadir al carrito' %}
</button>
</div> </div>
</div> </div>
</div> </div>
+8 -2
View File
@@ -1,6 +1,7 @@
from django.urls import path from django.urls import path
from web.views import index, list_products, product_detail from web.views import index, product_detail, add_cart_item, delete_cart_item
from web.components.views import list_products, cart_dropdown
app_name = "web" app_name = "web"
@@ -8,5 +9,10 @@ app_name = "web"
urlpatterns = [ urlpatterns = [
path("", index, name="index"), path("", index, name="index"),
path("products/<int:pk>/<str:slug>/", product_detail, name="product_detail"), path("products/<int:pk>/<str:slug>/", product_detail, name="product_detail"),
path("shop/components/products/", list_products, name="list_products"), # components
path("web/components/products/", list_products, name="list_products"),
path("web/components/cart-dropdown/", cart_dropdown, name="cart_dropdown"),
# api
path("web/add-cart-item/", add_cart_item, name="add_cart_item"),
path("web/delete-cart-item/<int:pk>/", delete_cart_item, name="delete_cart_item"),
] ]
+11
View File
@@ -0,0 +1,11 @@
from shop.models import Cart
from web.settings import ANONYMOUS_CART_ID_COOKIE_NAME
def get_cart(request):
if not request.user.is_authenticated:
uid = request.COOKIES.get(ANONYMOUS_CART_ID_COOKIE_NAME)
cart = Cart.objects.get(uuid=uid)
else:
cart = Cart.objects.filter(user=request.user).first()
return cart
+49 -20
View File
@@ -1,9 +1,11 @@
from django.shortcuts import get_object_or_404 from django.shortcuts import get_object_or_404
from django.views.generic import TemplateView from django.views.generic import TemplateView
from django.http.response import HttpResponse
from django.views.decorators.http import require_http_methods
from shop.filters import ProductFilter from shop.models import Product, Cart, CartItem
from shop.models import Product from web.utils import get_cart
from web.mixins import FilteredQuerysetMixin, PaginatedQuerysetMixin from web.settings import ANONYMOUS_CART_ID_COOKIE_NAME
class IndexView(TemplateView): class IndexView(TemplateView):
@@ -15,22 +17,6 @@ class IndexView(TemplateView):
} }
class ListProducts(TemplateView, FilteredQuerysetMixin, PaginatedQuerysetMixin):
template_name = "web/list_products.html"
queryset = Product.objects.all()
filter_class = ProductFilter
def get_context_data(self, **kwargs):
qs = self.get_queryset()
page = self.get_paginated_queryset(qs)
return {
"page": page,
"has_next_page": page.has_next(),
"has_previous_page": page.has_previous(),
}
class ProductDetail(TemplateView): class ProductDetail(TemplateView):
template_name = "web/product_detail.html" template_name = "web/product_detail.html"
@@ -45,6 +31,49 @@ class ProductDetail(TemplateView):
} }
@require_http_methods(
[
"POST",
]
)
def add_cart_item(request, *args, **kwargs):
product = get_object_or_404(Product, pk=request.POST.get("product"))
response = HttpResponse(status=201)
if not request.user.is_authenticated:
cart = Cart.objects.create(
user=None,
)
else:
cart, created = Cart.objects.get_or_create(user=request.user)
response.set_cookie(ANONYMOUS_CART_ID_COOKIE_NAME, cart.uuid)
existing_cart_item = CartItem.objects.filter(cart=cart, product=product).first()
if existing_cart_item is not None:
existing_cart_item.quantity += int(request.POST.get("quantity"))
existing_cart_item.save()
else:
CartItem.objects.create(
cart=cart,
quantity=request.POST.get("quantity"),
product=product,
)
return response
@require_http_methods(
[
"POST",
]
)
def delete_cart_item(request, pk, *args, **kwargs):
cart = get_cart(request)
cart_item = get_object_or_404(CartItem, pk=pk, cart=cart)
cart_item.delete()
return HttpResponse(status=204)
index = IndexView.as_view() index = IndexView.as_view()
list_products = ListProducts.as_view()
product_detail = ProductDetail.as_view() product_detail = ProductDetail.as_view()