当我尝试以用户身份登录时,在mixins中出错

时间:2017-03-15 17:59:17

标签: python django

我创建了一个订单页面,客户可以查看他过去完成的所有订单,但我希望客户登录并查看订单所以我创建了一个loginrequiredmixin

mixins.py

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from carts.models import Cart
from .models import Order


class LoginRequiredMixin(object):
    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(LoginRequiredMixin, self).dispatch(request,*args, **kwargs)



class CartOrderMixin(object):
    def get_order(self, *args, **kwargs):
        cart = self.get_cart()
        if cart is None:
            return None
        new_order_id = self.request.session.get("order_id")
        if new_order_id is None:
            new_order = Order.objects.create(cart=cart)
            self.request.session["order_id"] = new_order.id
        else:
            new_order = Order.objects.get(id=new_order_id)
        return new_order

    def get_cart(self, *args, **kwargs):
        cart_id = self.request.session.get("cart_id")
        if cart_id == None:
            return None
        cart = Cart.objects.get(id=cart_id)
        if cart.items.count() <= 0:
            return None
        return cart

views.py

from django.shortcuts import render
from django.views.generic.edit import CreateView, FormView
from  django.views.generic.list import ListView
# Create your views here.
from .mixins import CartOrderMixin, LoginRequiredMixin
from .models import 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)

models.py

from decimal import Decimal
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save

# Create your models here.
from carts.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) #--> required


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

ORDER_STATUS_CHOICES = (
        ('created', 'Created'),
        ('completed', 'Completed')
    )       

class Order(models.Model):
    status = models.CharField(max_length=120, choices=ORDER_STATUS_CHOICES, default ='created')
    cart = models.ForeignKey(Cart)
    user = models.ForeignKey(UserCheckout, null=True)
    #shipping_address = models.ForeignKey
    #final_total_price = models.DecimalField(default=)
    order_total = models.DecimalField(max_digits=50, decimal_places=2,)
    #orderid
    def __unicode__(self):
        return str(self.cart.id)

    def mark_completed(self):
        self.status = "completed"
        self.save()     

def order_pre_save(sender, instance, *args, **kwargs):
    cart_total = instance.cart.total
    order_total = Decimal(cart_total)
    instance.order_total = order_total

pre_save.connect(order_pre_save, sender=Order)

错误

DoesNotExist at /orders/
UserCheckout matching query does not exist.
Request Method: GET
Request URL:    http://127.0.0.1:8000/orders/
Django Version: 1.8.4
Exception Type: DoesNotExist
Exception Value:    
UserCheckout matching query does not exist.
Exception Location: /Users/apulgupta/Desktop/ecommerce-2/Try-Django-1.8/lib/python2.7/site-packages/django/db/models/query.py in get, line 334
Python Executable:  /Users/apulgupta/Desktop/ecommerce-2/Try-Django-1.8/bin/python
Python Version: 2.7.10
Python Path:    
['/Users/apulgupta/Documents/ecommerce-2-before-guest-save/Try-Django-1.8/src',
 '/Users/apulgupta/Desktop/ecommerce-2/Try-Django-1.8/lib/python27.zip',
 '/Users/apulgupta/Desktop/ecommerce-2/Try-Django-1.8/lib/python2.7',
 '/Users/apulgupta/Desktop/ecommerce-2/Try-Django-1.8/lib/python2.7/plat-darwin',
 '/Users/apulgupta/Desktop/ecommerce-2/Try-Django-1.8/lib/python2.7/plat-mac',
 '/Users/apulgupta/Desktop/ecommerce-2/Try-Django-1.8/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/apulgupta/Desktop/ecommerce-2/Try-Django-1.8/lib/python2.7/lib-tk',
 '/Users/apulgupta/Desktop/ecommerce-2/Try-Django-1.8/lib/python2.7/lib-old',
 '/Users/apulgupta/Desktop/ecommerce-2/Try-Django-1.8/lib/python2.7/lib-dynload',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/apulgupta/Desktop/ecommerce-2/Try-Django-1.8/lib/python2.7/site-packages']
Server time:    Wed, 15 Mar 2017 17:42:22 +0000

一旦我获得登录页面并尝试登录,我就会收到上述错误

2 个答案:

答案 0 :(得分:1)

那是因为UserCheckout.objects.get(id=user_check_id)失败了。

你应该抓住任何潜在的失败:

try:
    user_checkout = UserCheckout.objects.get(id=user_check_id)
except UserCheckout.DoesNotExist as e:
    # do something if UserCheckout obj with user_check_id does not exist
else:
    # user_checkout succeeded. Procceed

如果对象不存在,您可以抛出404页

from django.shortcuts improt get_object_or_404

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

答案 1 :(得分:0)

我宁愿说这更像是一个错误的逻辑错误:|

在上面的代码中,我试图比较两个数量,即用户名id和用户的电子邮件地址id导致该错误。因此,我决定通过使用用户名和电子邮件地址作为一个整体,然后比较适合我的

来简化事情

编辑 views.py

from django.shortcuts import render
from django.views.generic.edit import CreateView, FormView
from  django.views.generic.list import ListView
# Create your views here.
from .mixins import CartOrderMixin, LoginRequiredMixin
from .models import UserCheckout, Order

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

    def get_queryset(self):
        user_check_id = self.request.user.email
        template_name = 'orders/order_list.html'
        print user_check_id
        user_checkout = UserCheckout.objects.get(email=user_check_id)
        print user_checkout
        return super(OrderList, self).get_queryset().filter(user=user_checkout)