#python #django #web #e-commerce
#python #django #веб #электронная коммерция
Вопрос:
Я запускаю Django и пытаюсь создать сайт электронной коммерции. Я работаю с итогами в своей корзине, чтобы получить следующее:
- Общее количество товаров в корзине
- Извлеките все элементы корзины
- Общая стоимость всех товаров.
мой код выглядит следующим образом
models.py
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
def __str__(self):
return str(self.id)
@property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
@property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
строка 54 в models.py есть
total = sum([item.get_total for item in orderitems])
views.py
def cart(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
else:
# Create empty cart for now for non-logged in user
items = []
order = {'get_cart_total': 0, 'get_cart_items': 0}
context = {'items': items, 'order': order}
return render(request, 'IT6041App/cart.html', context)
cart.html
{% extends "IT6041App/base.html" %}
{% load static %}
{% block content %}
<br><br><br>
<div class="row justify-content-md-center">
<div class="col-lg-6">
<br>
<div class="box-element">
<div class="cart-row">
<a class="btn btn-outline-dark" href="{% url 'index' %}">Continue Shopping</a>
<div style="flex:1"></div>
<div style="flex:1" align="center"><strong>Item</strong></div>
<div style="flex:1" align="center"><strong>Price</strong></div>
<div style="flex:1" align="center"><strong>Quantity</strong></div>
<div style="flex:1" align="center"><strong>Total</strong></div>
</div>
{% for item in items %}
<div class="cart-row">
<div style="flex:2"><img class="row-image" src="{{ item.product.imageURL }}"></div>
<div style="flex:1" align="center"><p>{{ item.product.product_name }}</p></div>
<div style="flex:1" align="center"><p>{{ item.product.price|floatformat:2 }}</p></div>
<div style="flex:1" align="center">
<p class="quantity">{{ item.quantity }}</p>
<div class="quantity">
<img class="chg-quantity" src="{% static 'media/arrow-up.png' %}">
<img class="chg-quantity" src="{% static 'media/arrow-down.png' %}">
</div>
</div>
<div style="flex:1" align="center"><p>${{ item.get_total|floatformat:2 }}</p></div>
</div>
{% endfor %}
</div>
<br>
<div class="box-element">
<br><br>
<table class="table">
<tr>
<th><h5>Items: <strong>{{ order.get_cart_items }}</strong></h5></th>
<th colspan="2" id="total-cost"><h5>Total:<strong>{{ order.get_cart_total|floatformat:2 }}</strong></h5></th>
<th>
<a style="float:right; margin:5px;" class="btn btn-success" href="{% url 'checkout' %}">Checkout</a>
</th>
</tr>
</table>
</div>
</div>
</div>
<br><br><br>
{% endblock content%}
моя ошибка заключается в следующем
TypeError at /cart/
unsupported operand type(s) for : 'int' and 'str'
Request Method: GET
Request URL: http://127.0.0.1:8000/cart/
Django Version: 3.0.5
Exception Type: TypeError
Exception Value:
unsupported operand type(s) for : 'int' and 'str'
Exception Location: C:UsersmackmOneDriveDocumentsGitHubIT6041WebIT6041Appmodels.py in get_cart_total, line 54
Python Executable: C:UsersmackmPycharmProjectsIT6041-ProjectvenvScriptspython.exe
Python Version: 3.8.5
Python Path:
['C:\Users\mackm\OneDrive\Documents\GitHub\IT6041Web',
'C:\Users\mackm\AppData\Local\Programs\Python\Python38-32\python38.zip',
'C:\Users\mackm\AppData\Local\Programs\Python\Python38-32\DLLs',
'C:\Users\mackm\AppData\Local\Programs\Python\Python38-32\lib',
'C:\Users\mackm\AppData\Local\Programs\Python\Python38-32',
'C:\Users\mackm\PycharmProjects\IT6041-Project\venv',
'C:\Users\mackm\PycharmProjects\IT6041-Project\venv\lib\site-packages']
Server time: Tue, 10 Nov 2020 10:42:07 0000
полная ошибка здесь
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/cart/
Django Version: 3.0.5
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'IT6041App.apps.IT6041appConfig',
'users.apps.UsersConfig',
'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template C:UsersmackmOneDriveDocumentsGitHubIT6041WebIT6041ApptemplatesIT6041Appbase.html, error at line 0
unsupported operand type(s) for : 'int' and 'str'
1 : {% load static %}
2 :
3 : <!doctype html>
4 : <html lang="en">
5 : <head>
6 : <meta charset="utf-8">
7 : <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
8 : <meta name="description" content="">
9 : <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
10 : <meta name="generator" content="Jekyll v4.1.1">
Traceback (most recent call last):
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 828, in _resolve_lookup
current = current[bit]
During handling of the above exception ('Order' object is not subscriptable), another exception occurred:
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangocorehandlersexception.py", line 34, in inner
response = get_response(request)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangocorehandlersbase.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangocorehandlersbase.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersmackmOneDriveDocumentsGitHubIT6041WebIT6041Appviews.py", line 22, in cart
return render(request, 'IT6041App/cart.html', context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangoshortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplateloader.py", line 62, in render_to_string
return template.render(context, request)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebackendsdjango.py", line 61, in render
return self.template.render(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 171, in render
return self._render(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 163, in _render
return self.nodelist.render(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 936, in render
bit = node.render_annotated(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 903, in render_annotated
return self.render(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplateloader_tags.py", line 150, in render
return compiled_parent._render(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 163, in _render
return self.nodelist.render(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 936, in render
bit = node.render_annotated(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 903, in render_annotated
return self.render(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplateloader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 936, in render
bit = node.render_annotated(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 903, in render_annotated
return self.render(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 986, in render
output = self.filter_expression.resolve(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 670, in resolve
obj = self.var.resolve(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 795, in resolve
value = self._resolve_lookup(context)
File "C:UsersmackmPycharmProjectsIT6041-Projectvenvlibsite-packagesdjangotemplatebase.py", line 836, in _resolve_lookup
current = getattr(current, bit)
File "C:UsersmackmOneDriveDocumentsGitHubIT6041WebIT6041Appmodels.py", line 54, in get_cart_total
total = sum([item.get_total for item in orderitems])
Exception Type: TypeError at /cart/
Exception Value: unsupported operand type(s) for : 'int' and 'str'
Что-то не так с моим base.html досье?
Я надеюсь, что кто-нибудь сможет мне здесь помочь.
Заранее благодарю вас
Класс OrderItems
class OrderItem(models.Model):
product = models.ForeignKey(Products, 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)
date_added = models.DateTimeField(auto_now_add=True)
@property
def get_total(self):
total = self.product.price * self.quantity
return total
Комментарии:
1. Если ваша ошибка в get_total, нам нужно взглянуть на метод get_total вашего класса OrderItem (и его поля). Но вы пытаетесь суммировать целое число со строкой, что невозможно.
2. Если вы хотите получить int, вы должны преобразовать str в int, и наоборот.
3. Потому
get_total
что возвращает строку , а неint
/float
/ другой числовой тип.4. Элементы заказа добавлены в основной пост.
Ответ №1:
Мне пришлось изменить общее значение на значение с плавающей запятой, прежде чем передавать его в класс Order для рендеринга. теперь это работает просто отлично.
class OrderItem(models.Model):
product = models.ForeignKey(Products, 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)
date_added = models.DateTimeField(auto_now_add=True)
@property
def get_total(self):
total = fload(self.product.price) * float(self.quantity)
return total