Richard
Richard

Reputation: 25

Unresolved reference 'models'

I am writing custom template tag, and the error occurs that "Unresolved reference 'models'" the following is my blog_tags.py.

from django import template

from .models import Post

register = template.Library()


@register.simple_tag
def total_posts():
    return Post.published.count()

And my directory tree is as followed

blog/
  __init__.py 
  models.py 
  ...
  templatetags/
     __init__.py
     blog_tags.py

And i do have a Post class in my Models.

And when i click the prompt by pycharm "install package Post", after finishing installed it, the error disappear. I wonder do i have to do the same, which is install the package by the IDE, every time when i want to write a custom tag evolved with class in my Models?

Upvotes: 1

Views: 3518

Answers (3)

Renjith Thankachan
Renjith Thankachan

Reputation: 4346

import your models with app namespace instead of relative import, so that the standard structure is maintained.

from django import template

# blog is your app name
from blog.models import Post

register = template.Library()


@register.simple_tag
def total_posts():
    return Post.published.count()

Please check here unresolved error issue related to pycharm in django projects

Upvotes: 0

j-i-l
j-i-l

Reputation: 10967

As this is Django and as in Django circular imports can be an issue, consider dynamically loading the model:

for django 1.7+ use the application registry:

from django.apps import apps
Post = apps.get_model('blog', 'Post')

for earlier versions:

from django.db.models.loading import get_model
Post = get_model('blog', 'Post')

Note: This only works if 'blog' is an installed app.

Upvotes: 1

Sören Weber
Sören Weber

Reputation: 589

If I'm interpreting your project structure correctly, your models module is located in a parent package relative to blog_tags. Accessing .models would try to find the module inside your templatetags package.

Try to change your import to this instead:

from ..models import Post

Upvotes: 5

Related Questions