1

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?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Richard
  • 25
  • 1
  • 8

3 Answers3

5

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
Sören Weber
  • 601
  • 6
  • 25
1

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.

j-i-l
  • 10,281
  • 3
  • 53
  • 70
0

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

Community
  • 1
  • 1
Renjith Thankachan
  • 4,178
  • 1
  • 30
  • 47