我有一个包含一些产品的表,每个表旁边都有一个添加到购物车按钮,可将product.in_cart布尔值更改为true。当我单击按钮时,值会更改,但我不会转到所需的URL(add_to_cart / product_id)。我想重定向到索引(产品列表)。我怎样才能做到这一点?

我还收到一条错误消息:视图products.views.add_to_cart没有返回HttpResponse对象。

这是我的代码:

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')
]


谢谢 :)

最佳答案

return redirect('index')的末尾添加add_to_cart

10-04 12:44