将 POST 请求重定向到 URL 已使用 (Django)

Redirect POST request to URL already used (Django)

我有一个 table,其中包含一些产品,每个产品旁边都有一个 添加到购物车 按钮,用于更改产品。in_cart 布尔值设为真。当我单击按钮时,值发生变化,但我不会转到我想要的 URL (add_to_cart/product_id)。我想被重定向到索引(产品列表)。我该怎么做?

我还收到一条错误消息:视图 products.views.add_to_cart 没有 return 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')
]

谢谢:)

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

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是urls.py中定义的名称(path('cart/',views.cart,name='cart'))

从django.shortcuts导入重定向