Я попытался включить опцию удаления в корзине, чтобы удалить элемент корзины, добавив некоторый код, в результате появилPython

Программы на Python
Ответить
Anonymous
 Я попытался включить опцию удаления в корзине, чтобы удалить элемент корзины, добавив некоторый код, в результате появил

Сообщение Anonymous »

Я добавил код, чтобы включить опцию удаления в корзине. возникает следующая ошибка.
Обратный вариант для «remove_cart_item» с аргументами «(2,)» не найден. Опробовано 1 шаблон(ы): ['cart/remove_cart_item/(?P
[0-9]+)/(?P[0-9]+)/$']
cart.html
{% extends 'base.html' %}
{% load static %}

{% block content %}


{% if not cart_items%}
Your shopping cart is empty

Continue Shopping

{% else %}

{{cart_item.product.product_name}}

{% if cart_item.variations.all %}
{% for item in cart_item.variations.all %}
{{item.variation_category |capfirst }} : {{item.variation_value | capfirst}}

{% endfor %}
{% endif %}









[/i]




{% csrf_token %}
{% for item in cart_item.variations.all %}

{% endfor %}








${{cart_item.sub_total}}
${{cart_item.product.price}} each



Remove


{% endfor %}





Checkout
Continue Shopping






{% endif %}






{% endblock %}

файл urls.py приложения корзин
urlpatterns = [
path('', views.cart, name='cart'),
path('add_cart//', views.add_cart, name='add_cart'),
path('remove_cart///', views.remove_cart, name='remove_cart'),
path('remove_cart_item///', views.remove_cart_item, name='remove_cart_item'),

]

файлviews.py приложения корзин

# Create your views here.
def _cart_id(request):
cart = request.session.session_key
if not cart:
cart = request.session.create()
return cart

def add_cart(request, product_id):
product = Product.objects.get(id=product_id) #get the product
product_variation = []
if request.method=='POST':
for item in request.POST:
key=item
value=request.POST[key]

try:
variation=Variation.objects.get(product=product, variation_category__iexact=key, variation_value__iexact=value)
product_variation.append(variation)
except:
pass

try:
cart = Cart.objects.get(cart_id = _cart_id(request)) #get the cart using the cart_id present in the session
except Cart.DoesNotExist:
cart = Cart.objects.create(
cart_id = _cart_id(request)
)
cart.save()

is_cart_item_exists = CartItem.objects.filter(product=product, cart=cart).exists()
if is_cart_item_exists:
cart_item = CartItem.objects.filter(product=product, cart=cart)
# existing_variations ->database
# current_variations -> product_variation
# item_id -> database
ex_var_list = []
id = []
for item in cart_item:
existing_variation = item.variations.all()
ex_var_list.append(list(existing_variation))
id.append(item.id)

print(ex_var_list)

if product_variation in ex_var_list:
# increase the cart item quantity
index = ex_var_list.index(product_variation)
item_id = id[index]
item = CartItem.objects.get(product=product, id=item_id)
item.quantity += 1
item.save()
else:
# create a new cart item
item = CartItem.objects.create(product=product, quantity=1, cart=cart)
if len(product_variation) > 0:
item.variations.clear()
item.variations.add(*product_variation)
item.save()
else:
cart_item = CartItem.objects.create(
product = product,
quantity = 1,
cart = cart,
)
if len(product_variation) > 0:
cart_item.variations.clear()
cart_item.variations.add(*product_variation)
cart_item.save()

return redirect('cart')

def remove_cart(request, product_id, cart_item_id):
cart = Cart.objects.get(cart_id = _cart_id(request))
product = get_object_or_404(Product, id=product_id)
try:
cart_item = CartItem.objects.get(product = product, cart = cart, id=cart_item_id)
if cart_item.quantity > 1:
cart_item.quantity -= 1
cart_item.save()
else:
cart_item.delete()
except:
pass
return redirect('cart')

def remove_cart_item(request, product_id, cart_item_id):
cart = Cart.objects.get(cart_id = _cart_id(request))
product = get_object_or_404(Product, id=product_id)
cart_item = CartItem.objects.get(product = product, cart = cart, id=cart_item_id)
cart_item.delete()
return redirect('cart')

def cart(request, total=0, quantity=0, cart_items= None):
try:
tax = 0
grand_total = 0
cart = Cart.objects.get(cart_id = _cart_id(request))
cart_items = CartItem.objects.filter(cart=cart, is_active=True)
for cart_item in cart_items:
total += (cart_item.product.price * cart_item.quantity)
quantity += cart_item.quantity
tax = (total * 2) / 100
grand_total = total + tax

except ObjectDoesNotExist:
pass # just ignore
context = {
'total': total,
'quantity': quantity,
'cart_items': cart_items,
'tax': tax,
'grand_total': grand_total,
}

return render(request, 'store/cart.html', context)

def __str__(self):
return self.cart_item

стек трассировки
Internal Server Error: /cart/
Traceback (most recent call last):
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\carts\views.py", line 124, in cart
return render(request, 'store/cart.html', context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 170, in render
return self._render(context)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\defaulttags.py", line 312, in render
return nodelist.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\defaulttags.py", line 211, in render
nodelist.append(node.render_annotated(context))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\template\defaulttags.py", line 446, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\GreatKart\env\Lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'remove_cart_item' with arguments '(2,)' not found. 1 pattern(s) tried: ['cart/remove_cart_item/(?P[0-9]+)/(?P[0-9]+)/$']


Подробнее здесь: https://stackoverflow.com/questions/792 ... ing-the-so
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»