Home > front end >  My view object 'has no attribute' {my attribute} in Django
My view object 'has no attribute' {my attribute} in Django

Time:01-28

Background

I'm trying to load a custom url (e.g. www.mysite.com/order-2523432) that will show a user details about their order.

Problem

I am trying to use the method order_id in my models.py in order to get the correct url. The problem is that I am getting the error:

'OrderDetailView' object has no attribute 'order_id'

Does anyone know what I can do to get order_id to work?

My views.py:

class OrderDetailView(DetailView):
    model = Orders
    template_name = "customer/orders.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        try:
            context["orders"] = get_orders(self)
        except RequestException as e:
            logger.exception(e)
        return context

My utils.py:

def get_orders(orders):
    url = f"mysite.com/customer/{orders.order_id}"
    method = "GET"
    content_type = "application/json"
    header = Sender(
        credentials etc
    ).request_header
    response = requests.request(
        headers etc
    )
    response.raise_for_status()
    return response.json()

My models.py:

class Orders(CustomModel):
    table_name = models.CharField(max_length=256, unique=True)

    @property
    def order_id(self):
        return f"order-{self.table_name}"

    def get_absolute_url(self):
        return reverse("order:edit", args=(self.id,))

CodePudding user response:

you should use self.object or context['object'] or get_object() instead of passing self
please try this:

class OrderDetailView(DetailView):
    model = Orders
    template_name = "customer/orders.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        try:
            context["orders"] = get_orders(context['object'])
        except RequestException as e:
            logger.exception(e)
        return context
  •  Tags:  
  • Related