python - Django url 不带参数

标签 python django django-urls

我真的很难理解将参数和关键字参数分派(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 ,我能够使用像 "localhost:8000/cart/?item=4&qty=200" 这样的 url 中的参数,并在终端中打印带有数量的项目。

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

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.

url.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)

并且意味着您没有与给定 id 匹配的 Variation 对象。

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

相关文章:

python - 我可以使用 C 模块绕过 python GIL 吗?

Python - 对列进行多个条件分组

python - 在 ZeroRPC 中实现自定义队列

python - Python Django 是否支持没有外键关系的自定义 SQL 和非规范化数据库?

python - 是否可以从字符串制作 Django urlpatterns?

python - 构造2个具有固定相关性的时间序列随机变量

python - Websocket 与 Django 中的 Channels 断开连接

python - Django通过外键查询订单(反方向)

python - Django:如何解码url以获取变量值?

python - django在html之间传输变量