django ::: UserCheckout匹配查询中不存在基于过滤类的视图(Listview)

时间:2018-11-13 19:32:34

标签: python django django-views django-class-based-views class-based-views

请尝试解决此问题,但无法解决。 每当我尝试加载订单网址locahost:8000 / orders / 时,都会出现此错误页面

DoesNotExist at /orders/

UserCheckout matching query does not exist.

Request Method:     GET
Request URL:    http://localhost:8000/orders/

Django Version:     1.8.4

Exception Type:     DoesNotExist

Exception Value:    UserCheckout matching query does not exist.

Exception Location:     /home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/db/models/query.py in get, line 334
Python Executable:  /usr/local/bin/uwsgi
Python Version:     3.6.0
Python Path:    

['/home/rayup/hotels',
 '/var/www',
 '.',
 '',
 '/var/www',
 '/home/rayup/.virtualenvs/secondenv/lib/python36.zip',
 '/home/rayup/.virtualenvs/secondenv/lib/python3.6',
 '/home/rayup/.virtualenvs/secondenv/lib/python3.6/lib-dynload',
 '/usr/lib/python3.6',
 '/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages']

Server time:    Tue, 13 Nov 2018 18:39:47 +0000

请在这里找到追溯 :::

Environment:


Request Method: GET
Request URL: http://www.rayconsult.com.ng/orders/

Django Version: 1.8.4
Python Version: 3.6.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'shop',
 'orders',
 'crispy_forms',
 'django_filters',
 'registration',
 'bootstrap3',
 'cart',
 'contact',
 'newsletter',
 'newsletter1',
 'django.contrib.sites']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Traceback:
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/rayup/hotels/orders/mixins.py" in dispatch
  11.       return super(LoginRequiredMixin, self).dispatch(request,*args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
  89.         return handler(request, *args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/views/generic/list.py" in get
  159.         self.object_list = self.get_queryset()
File "/home/rayup/hotels/orders/views.py" in get_queryset
  40.       user_checkout = UserCheckout.objects.get(id=user_check_id)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
  127.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/db/models/query.py" in get
  334.                 self.model._meta.object_name

Exception Type: DoesNotExist at /orders/
Exception Value: UserCheckout matching query does not exist.

我的 views.py 中的这一行代码导致了该问题:

user_checkout = UserCheckout.objects.get(id=user_check_id)

我的 views.py 中有一个名为 OrderList 的基于类的视图。

基本上,我希望登录时模板中返回的列表(订单列表)特定于每个用户

这是我的 views.py

from django.contrib import messages
from django.http import Http404
from django.shortcuts import render, redirect
from django.views.generic.edit import CreateView, FormView
from django.views.generic.detail import DetailView
from  django.views.generic.list import ListView


from .forms import AddressForm, UserAddressForm
from .mixins import CartOrderMixin, LoginRequiredMixin
from .models import UserAddress, UserCheckout, Order




class OrderList(LoginRequiredMixin, ListView):
    queryset = Order.objects.all()

    def get_queryset(self):
        user_check_id = self.request.user.id
        user_checkout = UserCheckout.objects.get(id=user_check_id)
        return super(OrderList, self).get_queryset().filter(user=user_checkout)


class OrderDetail(DetailView):
    model = Order

    def dispatch(self, request, *args, **kwargs):
        try:
            user_check_id = self.request.session.get("user_checkout_id")
            user_checkout = UserCheckout.objects.get(id=user_check_id)
        except UserCheckout.DoesNotExist:
            user_checkout = UserCheckout.objects.get(user=request.user)
        except:
            user_checkout = None

        obj = self.get_object()
        if obj.user == user_checkout and user_checkout is not None:
            return super(OrderDetail, self).dispatch(request, *args, **kwargs)
        else:
            raise Http404

这是 models.py

from decimal import Decimal
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import pre_save, post_save
from cart.models import Cart

class UserCheckout(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True) #not required
    email = models.EmailField(unique=True)
    braintree_id = models.CharField(max_length=120, null=True, blank=True)

    def __str__(self): #def __str__(self):
        return self.email

    @property
    def get_braintree_id(self,):
        instance = self
        if not instance.braintree_id:
            result = braintree.Customer.create({
                "email": instance.email,
            })
            if result.is_success:
                instance.braintree_id = result.customer.id
                instance.save()
        return instance.braintree_id

    def get_client_token(self):
        customer_id = self.get_braintree_id
        if customer_id:
            client_token = braintree.ClientToken.generate({
                "customer_id": customer_id
            })
            return client_token
        return None

class Order(models.Model):
    status = models.CharField(max_length=120, choices=ORDER_STATUS_CHOICES, default='created')
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE,  null=True)
    user = models.ForeignKey(UserCheckout, null=True)
    billing_address = models.ForeignKey(UserAddress, related_name='billing_address', null=True)
    shipping_address = models.ForeignKey(UserAddress, related_name='shipping_address', null=True)
    shipping_total_price = models.DecimalField(max_digits=50, decimal_places=2, default=5.99)
    order_total = models.DecimalField(max_digits=50, decimal_places=2, null=True )
    order_id = models.CharField(max_length=20, null=True, blank=True)

    def __str__(self):
        return str(self.cart.id)

    class Meta:
        ordering = ['-id']

    def get_absolute_url(self):
        return reverse("order_detail", kwargs={"pk": self.pk})

    def mark_completed(self, order_id=None):
        self.status = "paid"
        if order_id and not self.order_id:
            self.order_id = order_id
        self.save()

这是模板 order_list.html

{% if object_list|length <= 0 %}

<div class='col-sm-6 col-sm-offset-3 text-center'>
<p class='lead'>
You do not currently have orders.
</p>

</div>

{% else  %}

<div class='col-sm-6 col-sm-offset-3'>
<h1>Your Orders</h1>


<table class='table'>
{% for object in object_list %}

<tr>

<td>
<a href='{{ object.get_absolute_url }}'>View #{% if object.order_id %}{{ object.order_id }}{% else %}{{ object.id }}{% endif %}</a>

</td>
<td>
Item Count: {{ object.cart.items.count }}
</td>


</tr>

{% endfor %}

</table>
</div>
{% endif %}

这是订购页面

的主要网址(即项目网址 urls.py
urlpatterns = [
 url(r'^orders/$', OrderList.as_view(), name='orders'),
 url(r'^orders/(?P<pk>\d+)/$', OrderDetail.as_view(), name='order_detail'),
 ]

请我为您提供更多您需要的详细信息。 问题出在 def get_queryset(self):函数上。我需要能够对其进行自定义,使其仅基于当前登录用户的退货清单。 但是我可以访问每个单独的订单(即,通过键入管理员已知的URL来查看detailview。)

enter image description here 感谢并希望大家在这里

0 个答案:

没有答案