Edit:
My goal is to create a small e-commerce. In my index I have a list of products, one of the attributes is a boolean called in_cart which states if the product is in the cart or not. By default all boolean values are false. In my template is a table with all the products next to which I put a button "add to cart", which redirects to the cart template. However when I click on add to cart, the value of the boolean in question does not change to true. Any thoughts?
<table>
<tr>
<th>List of car parts available:</th>
</tr>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
{% for product in products_list %}
<tr>
<td>{{ product.id }}</td>
<td>{{ product.name }}</td>
<td>${{ product.price }}</td>
<td>{% if not product.in_cart %}
<form action="{% url 'add_to_cart' product_id=product.id %}" method="POST">
{% csrf_token %}
<input type="submit" id="{{ button_id }}" value="Add to cart">
</form>
{% else %}
{{ print }}
{% endif %}
</td>
</tr>
{% endfor %}
</table>
<a href="{% url 'cart' %}">See cart</a>
And these are my views:
def index(request):
if request.method == "GET":
products_list = Product.objects.all()
template = loader.get_template('products/index.html')
context = {'products_list': products_list}
return HttpResponse(template.render(context, request))
return HttpResponse('Method not allowed', status=405)
def cart(request):
cart_list = Product.objects.filter(in_cart = True)
template_cart = loader.get_template('cart/cart.html')
context = {'cart_list': cart_list}
return HttpResponse(template_cart.render(context, request))
def add_to_cart(request, product_id):
if request.method == 'POST':
try:
product = Product.objects.get(pk=product_id)
product.in_cart = True
product.save()
except Product.DoesNotExist:
return HttpResponse('Product not found', status=404)
except Exception:
return HttpResponse('Internal Error', status=500)
return HttpResponse('Method not allowed', status=405)
Model:
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.IntegerField()
in_cart = models.BooleanField(default=False)
ordered = models.BooleanField(default=False)
def __str__(self):
return self.name
URLs
urlpatterns = [
path('', views.index, name='index'),
path('cart/', views.cart, name='cart')
re_path(r'^add_to_cart/(?P<product_id>[0-9]+)$', views.add_to_cart, name='add_to_cart')
]
Error in my terminal
File "/Users/Nicolas/code/nicobarakat/labelachallenge/products/urls.py", line 8
re_path(r'^add_to_cart/(?P<product_id>[0-9]+)$', views.add_to_cart, name='add_to_cart')
^
SyntaxError: invalid syntax