Bhawesh Chaudhary
Bhawesh Chaudhary

Reputation: 88

Why django throwing error like " 'function' object has no attribute 'order_set' "?

I have edited views.py and after that it is throwing error like the screenshot below. enter image description here

Here are the codes.
/apps/views.py contains

from django.shortcuts import render
from django.http import HttpResponse
from .models import *
    
def customer(request, pk):
  customers = Customer.objects.get(id=pk)
    
   order = customer.order_set.all()
    
   context={'customers':customers, 'order':order}
   return render(request, 'accounts/customer.html',context)

and /templates/apps/name.html contains this code to render data from models to templates.

{% for i in order %}
 <tr>
    <td>{{i.product}}</td>
    <td>{{i.product.category}}</td>
    <td>{{i.date_created}}</td>
    <td>{{i.status}}</td>
    <td><a href="">Update</a></td>
    <td><a href="">Remove</a></td>
 </tr>
{% endfor %}

I think this error has something to do with order_ser in views.py but i am not sure how to fix it.

Upvotes: 1

Views: 155

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477170

You wrote customers = customer.objects.get(id=pk), but then you use customer.order_set, and here customer refers to the customer function. You should use customer:

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from .models import *
    
def customer(request, pk):
    #      ↓ without s
    customer = get_object_or_404(Customer, id=pk)
    order = customer.order_set.all()
    
    context={'customer': customer, 'order':order}
    return render(request, 'accounts/customer.html', context)

Note: It is often better to use get_object_or_404(…) [Django-doc], then to use .get(…) [Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using .get(…) will result in a HTTP 500 Server Error.

Upvotes: 2

Related Questions