3

I recently added a new method to my model "News":

def slug(self):
    return slugify(self.title)

However I can't seem to call it from 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 a total beginner at Django and Python and I'm sure this is just a stupid mistake on my side. By the way I tried restarting the dev server and syncing the db after I added the method, both don't change a thing. Note that I have used model methods like this before without a problem :S

Edit:

Here is 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 example code on how I call the method. I first tried to call it in a template, but it didn't work. Then I changed my view so it just returns the slug, but the error remains. Same when I try 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())
7
  • 3
    Can you post the model that slug if a part of and the code where you make the call to slug() Apr 4, 2012 at 13:19
  • Agree with Timmy, we don't have enough information now to answer your question. Apr 4, 2012 at 13:26
  • I can't see where you instance news. You need to do news = News.objects.get(pk=news_id)
    – Mikael
    Apr 4, 2012 at 13:31
  • Sorry yeah forgot that line :S Already edited in 10 seconds later.
    – cpury
    Apr 4, 2012 at 13:32
  • Hmmm, I think everything looks ok. Maybe you should try clearing your .pyc files: find . -name "*.pyc" -exec rm -r {} \; (or manually delete the models.pyc for the News model Apr 4, 2012 at 13:33

2 Answers 2

0

There are, no errors. Please check what class you by

  from fbki.models import News

it looks like you have two copies in project, and modify other class. You check by renaming your class News to News1. It you will same error - I'm right.

0

I've had some errors similar to this.

I believe that the problem is an inconsistency between your model and the actual schema in your database.

Run manage.py sql myapp and verify the contents match what is in sql> show schema (etc.)

If they don't match, you have to use your SQL client and drop the old table so that you can re-run manage.py syncdb to make them match again.

Your method should work once the schema are present.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.