gpt4 book ai didi

python - Django 网址不接受参数

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:51 25 4
gpt4 key购买 nike

我真的很难理解将参数和 keword 参数分派(dispatch)给 Django url 的方法。以下是案例研究:

我有一个使用通用基础 View 的 View :

class CartView(View):
def get(self, request, *args, **kwargs):
item = request.GET.get('item')
qty = request.GET.get('qty')
print item, qty
return HttpResponseRedirect('/')

通过上面的 View ,我能够在 url 中使用参数,如 "localhost:8000/cart/?item=4&qty=200" 并在终端中打印带有数量的项目。

一旦我对代码进行了更改,例如:

from carts.models import Cart, CartItem
from products.models import Variation


class CartView(View):
def get(self, request, *args, **kwargs):
item_id = request.GET.get('item')
if item_id:
item_instance = get_object_or_404(Variation, id=item_id)
qty = request.GET.get('qty')
cart = Cart.objects.all()[0]
cart_item = CartItem.objects.get_or_create(cart=cart, item=item_instance)[0]
cart_item.quantity = qty
cart_item.save()
print cart_item
return HttpResponseRedirect('/')

以同样的方式传递参数,如 "localhost:8000/cart/?item=4&qty=200" 它向我显示了错误:

404 Page Not Found No Variation matches the given query.

网址.py

urlpatterns = [
url(r'^home/$', 'newsletter.views.home', name='home'),
url(r'^contact/$', 'newsletter.views.contact', name='contact'),
url(r'^about/$', 'project.views.about', name='about'),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^cart/$', CartView.as_view(), name='cart'),
url(r'^', include('products.urls')),
url(r'^categories/', include('products.urls_categories')),

最佳答案

404 Page Not Found

No Variation matches the given query.

此消息来自您的线路:

item_instance = get_object_or_404(Variation, id=item_id)

并且意味着您没有匹配给定 idVariation 对象。

关于python - Django 网址不接受参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38092978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com