Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class meta got invalid attributes

Please help to fix this Meta class value as I gave up after detailed research. I am getting back error while trying to handle template urls with "get_absolute_url" as it responds with following error.

TypeError: 'class Meta' got invalid attribute(s): sale_price,get_absolute_url.

Below is my code.

class Meta:
        db_table = 'products'
        ordering = ['-created_at']

        def __unicode__(self):
            return self.name

        @models.permalink
        def get_absolute_url(self):
            return ('catalog_product', (), {'product_slug': self.slug})

        def sale_price(self):
            if self.old_price > self.price:
                return self.price
            else:
                return None

Thanks.

like image 555
Mudassar Hashmi Avatar asked Feb 11 '23 17:02

Mudassar Hashmi


1 Answers

You are misunderstanding how models are defined. You add your methods and attributes to the actual Model class and use the Meta class to specify options upon the class:

class MyModel(models.Model):
    old_price = ...
    price = ...
    slug = ...
    created_at = ...
    ...

    def __unicode__(self):
        return self.name

    @models.permalink
    def get_absolute_url(self):
        return ('catalog_product', (), {'product_slug': self.slug})

    def sale_price(self):
        if self.old_price > self.price:
            return self.price
        else:
            return None
    class Meta:
        db_table = 'products'
        ordering = ['-created_at']

Have a read of the Model documentation and pay attention to the section on Meta options

EDIT

Also, don't use the permalink decorator as it's no longer recommended:

https://docs.djangoproject.com/en/1.6/ref/models/instances/#the-permalink-decorator

The permalink decorator is no longer recommended. You should use reverse() in the body of your get_absolute_url method instead.

like image 106
Timmy O'Mahony Avatar answered Feb 18 '23 20:02

Timmy O'Mahony