Friday 6 August 2021

I am getting ERROR: AttributeError at /customer/5/ type object 'Customer' has no attribute 'orderitem_set'

Please help me I stuck at this problem. When Click on the view button I want to show all the orders from that user as shown in the image below, but when i click on it I am getting this error instead of order details for that customer.

enter image description here

The models file contains

models.py

class Customer(models.Model):
    user = models.OneToOneField(
        User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=50, null=True)
    phone = models.CharField(max_length= 200, null = True)
    email = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Order(models.Model):
    customer = models.ForeignKey(
        Customer, on_delete=models.SET_NULL, null=True, blank=True)
    date_ordered = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False, null=True, blank=True)
    transaction_id = models.CharField(max_length=200, null=True)

    def __str__(self):
        return str(self.customer)

    @property
    def shipping(self):
        shipping = False
        orderitems = self.orderitem_set.all()
        for i in orderitems:
            if i.product.digital == False:
                shipping = True
        return shipping

    @property
    def get_cart_total(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.get_total for item in orderitems])
        return total

    @property
    def get_cart_items(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.quantity for item in orderitems])
        return total    

class OrderItem(models.Model):
    product = models.ForeignKey(
        Product, on_delete=models.SET_NULL, null=True, blank=True)
    order = models.ForeignKey(
        Order, on_delete=models.SET_NULL, null=True, blank=True)
    quantity = models.IntegerField(default=0, null=True, blank=False)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.product.name

    @property
    def get_total(self):
        total = self.product.price * self.quantity
        return total

The views.py file contains Views.py

@login_required(login_url='login')
@admin_only
def customer(request, pk):
    customer = Customer.objects.get(id=pk)
    orders = Customer.orderitem_set.all()
    shippinginfo = customer.shippingaddress_set.all()

    total_order = orders.count()

    context = {'customer': customer, 'orders': orders, 'total_order':total_order, 'shippinginfo': shippinginfo}
    return render(request, 'store/customer.html', context)


from I am getting ERROR: AttributeError at /customer/5/ type object 'Customer' has no attribute 'orderitem_set'

No comments:

Post a Comment