【问题标题】:No Order matches the given query没有订单匹配给定的查询
【发布时间】:2021-11-21 11:27:14
【问题描述】:

我正在从名为 Django 3 的书中通过示例学习 Django。我正在按照书中给出的步骤进行操作。但我收到以下错误:

Page not found (404)
No Order matches the given query.
Request Method: GET
Request URL:    http://127.0.0.1:8000/payment/process/
Raised by:  payment.views.payment_process
Using the URLconf defined in FlixKart.urls, Django tried these URL patterns, in this order:

admin/
cart/
orders/
payment/ process/ [name='process']
The current path, payment/process/, matched the last one.

views.py 支付应用:

def payment_process(request):
    order_id = request.session.get('order_id')
    order = get_object_or_404(Order, id=order_id)
    total_cost = order.get_total_cost()
    if request.method == 'POST':
        # retrieve nonce
        nonce = request.POST.get('payment_method_nonce', None)
        # create and submit transaction
        result = gateway.transaction.sale({
            'amount': f'{total_cost:.2f}',
            'payment_method_nonce': nonce,
            'options': {
                'submit_for_settlement': True
            }
        })
        if result.is_success:
            # mark the order as paid
            order.paid = True
            # store the unique transaction id
            order.braintree_id = result.transaction.id
            order.save()
            return redirect('payment:done')
        else:
            return redirect('payment:canceled')
    else:
        # generate token
        client_token = gateway.client_token.generate()
        return render(request, 'payment/process.html', {'order': order,'client_token': client_token})

来自项目 urls.py 的 url 模式:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('cart/', include('cart.urls', namespace='cart')),
    path('orders/', include('orders.urls', namespace='orders')),
    path('payment/', include('payment.urls', namespace='payment')),
    path('', include('shop.urls', namespace='shop')),

]

我尝试了一些来自 stackoverflow 的解决方案,但没有一个对我有用。 请帮我解决这个错误。 谢谢。

【问题讨论】:

  • 您是否将您的网址列表放入设置中?
  • 是的,我已经做到了
  • 需要放入urls.py文件。建议你尝试过教程,Django的教程真不错docs.djangoproject.com/en/3.2/intro/tutorial01
  • 对不起。它已经在项目的 urls.py 中。我只是错误地提到我已将 url 放在 settings.py 中。但它已经在 urls.py

标签: python django django-models django-views django-templates


【解决方案1】:

页面解析正确,但错误No Order matches the given query提示404是由以下行引起的。

order = get_object_or_404(Order, id=order_id)

表示ID匹配order_id的记录在数据库中不存在,或者值为空。

【讨论】:

  • 好的。但是对此可能的解决方案是什么?
  • 你应该可以自己回答这个问题——不要陷入会话中order_id无效的情况
猜你喜欢
  • 2017-03-08
  • 2021-05-07
  • 2019-07-21
  • 1970-01-01
  • 2016-12-05
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
相关资源
最近更新 更多