colkas
colkas

Reputation: 585

Redirect POST request to URL already used (Django)

I have a table with a few products and next to each one there is a Add to cart button that changes the product.in_cart boolean value to true. When I click on the button, the value changes but I am not going to the URL I want (add_to_cart/product_id). I would like to be redirected to the index (list of products). How can I do that?

I also receive an error message: The view products.views.add_to_cart didn't return an HttpResponse object.

Here is my code:

index.html

<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>

views.py

def cart(request):
  if request.method == 'GET':
    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':
    product = Product.objects.get(pk=product_id)
    product.in_cart = True
    product.save()
    return redirect('index')

def remove_from_cart(request, product_id):
    if request.method == 'POST':
        product = Product.objects.get(pk=product_id)
        product.in_cart = False
        product.save()
        return redirect('cart')

urls.py

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'),
    re_path(r'^remove_from_cart/(?P<product_id>[0-9]+)$', views.remove_from_cart, name='remove_from_cart')
]

Thanks :)

Upvotes: 1

Views: 48

Answers (2)

Bruno Belloni
Bruno Belloni

Reputation: 41

def add_to_cart(request, product_id):   if request.method == 'POST':
    product = Product.objects.get(pk=product_id)
    product.in_cart = True
    product.save()
    return redirect('cart')

cart is the name defined in urls.py (path('cart/', views.cart, name='cart'))

also from django.shortcuts import redirect

Upvotes: 1

Alexandr Tatarinov
Alexandr Tatarinov

Reputation: 4034

Add return redirect('index') in the end of your add_to_cart.

Upvotes: 0

Related Questions