Problem loading custom template tags (Error: No module named x) - django

I am currently writing a few custom template tags but for some reason they will not load. My directory structure is as follows:
MyProj
|
----MyApp
|
|----templatetags
|
|----myapp_tags.py
|----__init__.py
In myapp_tags.py
from django.template import Library, Node
from myproj.myapp.models import Product
register = Library()
class LatestProductsNode(Node):
def render(self, context):
context['recent_products'] = Product.objects.all()[:5]
return ''
def get_latest_products(parser, token):
return LatestProductsNode()
get_latest_products = register.tag(get_latest_products)
In settings.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'myproj.myapp',
)
In the Template
{% load myapp_tags %}
The error i get when trying to load the page:
Exception Type: TemplateSyntaxError Exception Value:
'myapp_tags' is not a valid tag library: Could not load template library from django.templatetags.myapp_tags, No module named myapp_tags

in settings.py, you should never name the project 'myproj' explicitely. In INSTALLED_APPS, just use 'myapp'. Also, you should have this :
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.load_template_source',
)
And be sure to have an __init__.py in the myapp folder as well as in templatetags.
Use manage.py shell then from myapp.templatetags import myapp_tags to find out if theres any python error in the myapp_tags.py file.
Also, be sure that myapp_tags.py file name doesnt conflicts with another folder/file in your project.
Hope this helps.

One thing that's tripped me up is that the magic importing of templatetags bypasses the automatic reloading of the development server.
If the following works in manage.py shell
>>> from django.templatetags import myapp_tags
>>>
Then everything is actually working and you just need to reload the development server. If on the other hand you get an ImportError then something is wrong and you should check your INSTALLED_APPS, that you have an __init__.py file in the templatetags directory and all the other things suggested in the other answers.
This will probably only apply to a tiny fraction of the people who experience template tag loading problems, but this is the second time I've arrived at this question in as many weeks and both times it's just taken restarting the development server to get things working.

Some reasons:
due to error in templatetgs code.
If you have used model import in templatetags
For #2, for example. If you are doing:
from your_app2.models import model
This will go wrong, so instead above, you should do
from your_project.your_app2.models import model
It worked me this way.

I just came across the same problem in Django 2 and realized that the custom template tag files must have unique names across all of your project apps.

The problem is that nyapp_tags is not at the top level of an installed project. If you put myproj.myapp.templatetags in INSTALLED_APPS, you should be fine.

Related

Django / app import problem from submodule

I'm writing my own Django app, and trying to import submodule from my core library like that:
INSTALLED_APPS = [
'django.contrib.admin',
...
'core.login',
]
And interpreter gives me:
django.core.exceptions.ImproperlyConfigured:
Cannot import 'login'.
Check that 'core.login.apps.CustomloginConfig.name' is correct.
So login.apps looks like that
from django.apps import AppConfig
class CustomloginConfig(AppConfig):
name = 'login'
Are there any rules how I can edit this files to start Django properly?
apps.py file needs to be as so
from django.apps import AppConfig
class CustomloginConfig(AppConfig):
name = 'core.login'
This is where you tell django that I have registered this app 'core.login' and where to find it.
If login folder is in a core folder, then the above should work.
I think theres a lot of django apps out there that have organized things this way.
One being Kiwi but Im sure theres many others.

django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: thumbnail

I am developing a django web project that uses the following packages/applications:
sorl-thumbnail
django-oscar
Here is a snippet of my settings.py file:
INSTALLED_APPS = [
'registration', #should be immediately above 'django.contrib.auth'
'django.contrib.auth',
# ...
'zinnia',
'zinnia_tinymce',
'sorl.thumbnail',
'embed_video',
# ...
'django.contrib.flatpages',
'compressor',
'widget_tweaks',
] + get_core_apps()
When I comment out sorl.thumbnail, I am able to run the development server using manage.py runserver. However, if I uncomment the sorl.thumbnail line and try to run the development server, it throws an exception:
django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: thumbnail
Now, I am aware that a similar question exists on this site, however, following the instructions in the accepted solution, i.e.:
create a sol_thumbnail folder in same directory as the manage.py script
create sorl_thumbnail/apps.py (see below)
modify myproject/mysite/___init____.py (see below)
sorl-thumbnail/apps.py
from django.apps import AppConfig
class SorlthumbnailConfig(AppConfig):
name = 'sorl-thumbnail'
label = 'sorl.thumbnail'
myproject/mysite/_init _.py
default_app_config = 'sorl-thumbnail.apps.SorlthumbnailConfig'
Why is the fix above not working, and how do I resolve this issue?
BTW: I am using django-1.10
I went though the same problem of duplicated applications, and following exactly the similar question I solved my problem.
The problem with your solution is that you have added default_app_config = 'sorl-thumbnail.apps.SorlthumbnailConfig' to myproject/mysite/___init____.py, but you should have added to myproject/sorl-thumbnail/___init____.py.

Dotted name in AppConfig

With django 1.7 they added support for configuration classes instead of the magic string from previous versions.
My project has several applications into a folder named apps which is added to the PYTHON_PATH.
After adding a simple AppConfig derived class I'm running into many import errors and I want to rule out silly mistakes.
Suppose this structure:
project_root/
my_project/
apps/
my_app/
another_app/
Would it be correct to have this config?:
# my_app/apps.py
class MyAppConfig(AppConfig):
name = 'apps.my_app'
# my_app/__init__.py
default_app_config='apps.my_app.apps.MyAppConfig'
# settings.py
INSTALLED_APPS = (
...
'apps.myapp.apps.MyAppConfig'
...
)
Curently the project fails when trying to import models (or tasks or any other module) issuing:
from apps.my_app.tasks import AwesomeTask
ImportError: no module named my_app.tasks
I solved a similar issue by renaming the apps folder. It was somehow conflicting with Django internals system.
I hope this helps someone.

Django could not load template tag

I have created a templatetags folder inside my application and inside a file named posts.py, I have written the following code;
from django.template import Library, Node
from advancedviews.models import Post
register = Library()
class AllPost(Node):
def render(self,context):
context['all_posts'] = Post.objects.all()
return ''
def get_all_posts(parser,token):
return AllPost()
get_all_posts = register.tag(get_all_posts)
Now, I try to load this template tag inside my template;
{% load get_all_posts %}
But this gives me with error, 'get_all_posts' is not a valid tag library: Template library get_all_posts not found, tried django.templatetags.get_all_posts,django.contrib.admin.templatetags.get_all_posts
What is the error in this template or have I missed something here.
With load you need to use the name of the library, not the tag - so posts in your case.
(I assume you also have a blank __init__.py in the templatetags directory, and that the application is in INSTALLED_APPS).
suppose you have the following structure:
-- Application_Name
-------templatetags
--------------__init__.py
--------------templates_extras.py
-------__init__.py
-------settings.py
-- manage.py
You have to make sure of the following:
your application itself inside which your "templatetags" is resident is actually installed in INSTALLED_APPS in settings.py (e.g. "Application_Name")
your tag module itself that exists inside "templatetags" is already installed in INSTALLED_APP in settings.py (e.g. "ApplicationName.templatetags.tempaltes_extras")
keep sure you have "__init__.py" under templatetags directory
you have to restart the server
In some cases you have to remove all generated *.pyc if it did not work then retry again

How Django skipping an app when using syncdb command

I have a Django project which has two apps (one created as debug test). For the debug test, syncdb does put the model in the database but for the other it does not.
Both are in settings.INSTALLED_APPS.
There are around seven models, none of them being recognized.
Neither the server, any page or the syncdb-console give any errors.
Models are in a models directory. As a test, there is also one in app/models.py (doesn't work either).
Most strikingly to me is that the below code does display the models which aren't synced (executed from the app that is skipped):
for model in get_models():
models.append(model)
pass models to a template
Any help would be much appreciated. I think it is something trivial but I'm out of ideas for things to try.
Thanks,
UPDATE:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.admin',
'techtree',
'froink',
)
Structure:
project/techtree/models.py (contains a test model)
project/techtree/models/__init__.py (as described here)
project/techtree/models/typ.py (contains model Type)
There are more files of the same type as the last line.
Are you missing the __init__.py file in the second app's models directory? That would mean it can't be found on the path.
Can you show us your INSTALLED_APPS setting, and your directory structure please?
Looking at your directory structure, I think I can guess what's wrong.
my_app/
__init__.py
my_module.py
my_module/
__init__.py
my_python_file.py
With the above fictional directory structure, what gets imported when I do the following?
from my_module import *
Does that import everything from within my_module.py or everything within the my_module directory?
Use one, or the other. Not both. Put everything inside your models.py file, and get rid of the directory unless you have a good reason for having a models directory. You probably don't.
I faced this same problem, It took hours for me to figure out how to group models in to a separate directory. Heres how to do it,
Add a meta class to each of your models with an app_label parameter.
from django.db import models
class Test(models.Model):
class Meta:
app_label = 'myapp'
Here's where I found out about this,
Placing Django Models In Separate Files
But doing this wasn't enough you have to import the models in an __init__.py file in the models directory like this,
from YourModelFile import *
Django is usually searching for a models.py file only. If you have models.py and a module sub directory called models with an __init__.py file it is not recognizing the models correctly (my guess). You can do one of these two:
Remove your sub-module completely and keep all your model definitions in models.py
OR
Remove models.py in techtree. Add a models.py file to your techtree.models app where you keep the model definitions. Add 'techtree.models' to your INSTALLED_APPS (just 'techtree' is no enough).
Hope one of these answers helps.
Check the file name is
__init__.py
and not
init.py