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?

4
  • 1
    Try this: from blog.models import Post. Commented Apr 29, 2017 at 14:06
  • from ..models import Post if you want to make a relative import. . means from the same folder, so it is looking in templatetags where there is no models.py. Commented Apr 29, 2017 at 14:18
  • @nik_m I tried blog.models but it doesn't work, however the ..models worked Commented Apr 30, 2017 at 6:50
  • @jojo Thank you it, ..model worked, and i do learn from it! Commented Apr 30, 2017 at 6:50

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Sorry but what is circular import?
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

2 Comments

I've tried with blog.models, but it won't work. and with ..models worked
i support @jojo 's answer

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.