Django: AttributeError when calling native model method
I recently added a new method to my News model:
def slug(self):
return slugify(self.title)
However, I cannot name it anywhere. Imagine I have a News object called n. When trying to call
n.slug()
I always get an error like:
AttributeError: 'News' object has no attribute 'slug'
I'm new to Django and Python and I'm pretty sure this is just a stupid mistake on my side. BTW, I tried restarting the dev server and syncing the db after I added this method, both don't change anything. Note that I have used model methods like this with no problem: S
Edit:
Here's the model:
from django.template.defaultfilters import slugify
class News(models.Model):
title = models.CharField(max_length=100)
[...]
def slug(self):
return slugify(self.title)
Here is some sample code for how I call the method. At first I tried to call it a pattern, but it didn't work. Then I changed my view so that it just returns the slug, but the error remains. The same when I try to use it in the shell.
from fbki.models import News
def news_detail(request, slug, news_id):
news = News.objects.get(id = news_id)
return HttpResponse(news.slug())
source to share
I had some errors similar to this.
I believe the problem is an inconsistency between your model and the actual schema in your database.
Run manage.py sql myapp
and make sure the content matches what is in the sql> show schema (etc.)
If they don't match, you must use your SQL client and drop the old table to rerun manage.py syncdb
so they match again.
Your method should work as soon as the schema is present.
source to share