I have created a separate module (sources.py) in my django project in order to hold functions and keep my views module from turning into a complete nightmare.
When I import sources.py into views.py, call the function it holds, and run the code, with a print statement to make sure what is called is accurately being imported, everything works fine and I see printed what I expect.
However, when I try to run the app in the local server I get a ModuleNotFoundError.
If I include the code from the function in views and then run the local server, everything works just fine.
The module obviously is being imported otherwise the print statement wouldn't work. However, something is lost when trying to run on the local server.
I have gone through a ton of stackoverflow questions, python and django module tutorials, and questions located elsewhere and nothing has seemed to solved the problem. Below is all the code.
sources.py and views.py are both in the same directory. (betrTV/betrTV_app/file.py)
I have also tried " import sources * with original = sources.video() which provided the same issue as well as import . sources
from django.shortcuts import render
from django.http import HttpResponse
from datetime import date
from sources import video
''' returns a dict of unique video identifiers (last 11 chars)'''
original = video()
print(original)
sources = []
# strip out all except the unique source code
for i in range(len(original)):
source = original[i]
source = source[30:]
sources.append(source)
# Checked out... print(sources)
# create day of week to pull video
day = date.today()
num = str(day)[9]
# pull source from list by using 'num' from 'day'
source = sources[int(num)]
def index(request):
''' The home page for betrTV_app '''
video = 'class="video-frame" width="1200" height="600"\
+ src="https://www.youtube.com/embed/%s"\
+ frameborder="0" allow="accelerometer; autoplay; encrypted-media; \
+ gyroscope; picture-in-picture" allowfullscreen' %source
html = '<html><body><link href="https://fonts.googleapis.com/css?family=Gugi"\
+ rel="stylesheet"><h1 style="color: grey; font-family: Gugi; font-size: \
+ 20px;">BetrTV... Empowerment on Demand</h1>\
<iframe %s></iframe></body></html>' %video
return HttpResponse(html)
INSTALLED_APPS = [
...
# My Apps
'betrTV_app',
]
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Prometheus\Dropbox\LVL6\Programming\Python\betrTV\betrTV\urls.py", line 21, in <module>
path('', include('betrTV_app.urls')),
File "C:\Users\Prometheus\Envs\betr_env\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\Prometheus\Envs\betr_env\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Prometheus\Dropbox\LVL6\Programming\Python\betrTV\betrTV_app\urls.py", line 4, in <module>
from . import views
File "C:\Users\Prometheus\Dropbox\LVL6\Programming\Python\betrTV\betrTV_app\views.py", line 4, in <module>
from sources import video
ModuleNotFoundError: No module named 'sources'
Related
The problem below is raised after reviewing all the related SO questions, but unfortunately none of the answers brought a solution in my case (similar problem like: How to access Django models outside of Django?).
(with Django version: 4.1.1)
Having an application "simo" available with the related model, the db access works well from Django shell; but trying to access to it from outside Django as "scheduling.py", it just does not work.
import os
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
django.setup()
from django.db import models
from simo.models import Tasks
I tried to execute my python script in any folder:
beside manage.py,
beside settings.py and
beside models.py but none of them works.
[mysite]
[mysite]
[simo]
[migrations]
views.py
models.py
urls.py
__init__.py
apps.py
tests.py
admin.py
settings.py
urls.py
__init__.py
wsgi.py
asgi.py
scheduling.py
__init__.py
db.sqlite3
manage.py
The error received is:
C:\...\python.exe C:/.../mysite/scheduling.py
Traceback (most recent call last):
File "C:\...\mysite\scheduling.py", line 5, in <module>
django.setup()
File "C:\...\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\...\lib\site-packages\django\apps\registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "C:\...\lib\site-packages\django\apps\config.py", line 178, in create
mod = import_module(mod_path)
File "C:\...\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'simo'
Process finished with exit code 1
Could anyone advise me on how to resolve this issue?
Try calling
from django.db import models and from simo.models import Tasks before django.setup()
i use celery in django ,
i add a task to my project and get error, but before add this task my project is work good.
# app_account.celery_task.py
my first task is :
#shared_task
def send_birthday_email():
users = User.objects.filter(is_active=True, date_of_birth__isnull=False, email__isnull=False)
time = datetime.today()
for user in users:
if user.date_of_birth.day == time.day and user.date_of_birth.month == time.month:
send_mail(
f'happy birthday',
f'Happy birthday, dear {user.name}, have a good year',
'local#host.com',
[user.email],
)
my new task :
#shared_task
def send_password_reset_mail(mail_info):
send_mail(
subject=mail_info['subject'],
message=mail_info['message'],
from_email=mail_info['from_email'],
recipient_list=mail_info['recipient_list'],
)
second task use in this signal:
# this signal for send email reset password
#receiver(reset_password_token_created)
def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs):
email_plaintext_message = f"your token is = {reset_password_token.key}"
mail_info = {
'subject': 'Password Reset',
'message': email_plaintext_message,
'from_email': 'noreply#host.com',
'recipient_list': [reset_password_token.user.email],
}
send_password_reset_mail.delay(mail_info)
now , when i run by python manage.py runserver get this error
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/rahmanipy/Desktop/DrfBlog/venv/lib/python3.8/site-packages/django_rest_passwordreset/models.py", line 121, in <module>
UserModel = get_user_model()
File "/home/rahmanipy/Desktop/DrfBlog/venv/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 160, in get_user_model
return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
File "/home/rahmanipy/Desktop/DrfBlog/venv/lib/python3.8/site-packages/django/apps/registry.py", line 209, in get_model
app_config.import_models()
File "/home/rahmanipy/Desktop/DrfBlog/venv/lib/python3.8/site-packages/django/apps/config.py", line 301, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/rahmanipy/Desktop/DrfBlog/app_account/models.py", line 4, in <module>
from app_account.celery_tasks import send_password_reset_mail
File "/home/rahmanipy/Desktop/DrfBlog/app_account/celery_tasks.py", line 4, in <module>
from app_account.models import User
ImportError: cannot import name 'User' from partially initialized module 'app_account.models' (most likely due to a circular import) (/home/rahmanipy/Desktop/DrfBlog/app_account/models.py)
can anyone help me ???
You can inline import User inside your first task to avoid the circular import.
#shared_task
def send_birthday_email():
from app_account.models import User
users = User.objects.filter(is_active=True, date_of_birth__isnull=False, email__isnull=False)
time = datetime.today()
for user in users:
if user.date_of_birth.day == time.day and user.date_of_birth.month == time.month:
send_mail(
f'happy birthday',
f'Happy birthday, dear {user.name}, have a good year',
'local#host.com',
[user.email],
)
Integrating client project with pinax-notifications for notification kind of functionality.
*File "/home/user/Shwetha/ramble/ramble/rambleapp/urls.py", line 56, in <module>
url(r"^notifications/", include("pinax.notifications.urls", namespace="pinax_notifications")),
File "/home/user/.local/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/user/.local/lib/python3.6/site-packages/pinax/notifications/urls.py", line 3, in <module>
from .views import NoticeSettingsView
File "/home/user/.local/lib/python3.6/site-packages/pinax/notifications/views.py", line 5, in <module>
from .compat import login_required
File "/home/user/.local/lib/python3.6/site-packages/pinax/notifications/compat.py", line 12, in <module>
from account.decorators import login_required
File "/home/user/.local/lib/python3.6/site-packages/account/decorators.py", line 5, in <module>
from account.utils import handle_redirect_to_login
File "/home/user/.local/lib/python3.6/site-packages/account/utils.py", line 13, in <module>
from .models import PasswordHistory
File "/home/user/.local/lib/python3.6/site-packages/account/models.py", line 26, in <module>
class Account(models.Model):
File "/home/user/.local/lib/python3.6/site-packages/django/db/models/base.py", line 116, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class account.models.Account doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.*
As per the https://github.com/pinax/pinax-notifications#documentation Documentation , it was installed and configured. Encountered the above error while configuring.
Already tried:
In settings.py, INSTALLED_APPS section add both pinax and pinax-notifications.
Added Sites in INSTALLED_APPS and made SITE_ID=1 in settings.py.
verbose_name added in apps.py.
All the above does not seem to solve the problem. Please advise.
Background
I have recently started to learn Python Django. I read that it was good practice to have separate settings file for different environments. Consequently I have tried to implement something similar to what is describe in the "Simple Package Organization for Environments" section of this wiki: https://code.djangoproject.com/wiki/SplitSettings
Problem
When I now run a django-admin command I get a ModuleNotFoundError. Below I have copy pasted the error log I get for "django-admin check --deploy". "python manage.py runserver --settings=CollegeComp.settings.development" works fine.
Things I've tried
I was reading that I may have to reset the DJANGO_SETTINGS_MODULE environment variable in my virtual environment. I entered "set DJANGO_SETTINGS_MODULE=CollegeComp.settings.development" but I still get the same error.
Python path
When I type the following in the shell with my virtual environment activated:
import sys
print(sys.path)
I get the following:
['C:\\Users\\myusername\\Documents\\UdemyDjango\\MyPersonalProject\\College-Project-master\\CollegeComp',
'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\python37.zip',
'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\DLLs',
'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\lib',
'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv',
'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\lib\\site-packages']
Error log
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\Scripts\django-admin-script.py", line 10, in <module>
sys.exit(execute_from_command_line())
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 329, in run_from_argv
connections.close_all()
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\utils.py", line 220, in close_all
for alias in self:
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\utils.py", line 214, in __iter__
return iter(self.databases)
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\utils.py", line 147, in databases
self._databases = settings.DATABASES
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\conf\__init__.py", line 57, in __getattr__
self._setup(name)
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\conf\__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\conf\__init__.py", line 107, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'CollegeComp'
My project directory
CollegeComp
|-CollegeComp
|-settings
|-__init__.py
|-base.py
|-development.py
|-local.py
|-production.py
|-__init__.py
|-urls.py
|-wsgi.py
|-<my apps>
base.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
<rest of standard Django settings.py code>
development.py
from CollegeComp.settings.base import *
#Override base.py settings here
DEBUG = True
#Import local setting file
try:
from CollegeComp.settings.local import *
except:
pass
local.py
from CollegeComp.settings.base import *
#Override base settings here
DEBUG = True
production.py
from CollegeComp.settings.base import *
#Override base settings here
DEBUG = False
#Import local setting file
try:
from CollegeComp.settings.local import *
except:
pass
System info
Django version 2.1
Operating system: Windows 10
Python version: 3.7.0
I am grateful for any help I can get.
I wrote an app with abstract classes, some utils functions, my common template tags and so on.
Somewere I saw it's recommended way to do this stuff to a reusable app. (It's all related to each other.) Why not? It seems to be a good idea. So I made the stuff being part of an app. Since that app has no urls, views and not the normal structur, it's more like a python module. (But it needs django.)
When I import this app the normal way (with import myapp on top of the files) it works fine.
Looking for bestpractice I saw in the official django tutorial part 8 that's recommended to import apps in INSTALLED_APPS in settings.py. Since I made my utils module being an app I thought I could just add a line to INSTALLED_APPS. Just like this: myapp.apps.MyappConfig.
My project structure:
project
|-... [multiple normal apps]
|-myapp [which is my utils app]
|-project [the inner folder]
|-... [some other stuff]
As you can see, myapp, the utils app, is still part of the project (and hasn't been made a reusable app yet.)
But when I add that line to INSTALLED_APPS I get the following traceback:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0xb6356adc>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 250, in raise_last_exception
six.reraise(*_exception)
File "/usr/local/lib/python3.5/dist-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 94, in create
module = import_module(entry)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/my_cool_directory/project/myapp/__init__.py", line 1, in <module>
from .models import *
File "/my_cool_directory/project/myapp/models.py", line 8, in <module>
class Publishable(models.Model):
File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 110, in __new__
app_config = apps.get_containing_app_config(module)
File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 247, in get_containing_app_config
self.check_apps_ready()
File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 125, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
It's not like I have I serious problem because I can import the app the normal way. I'm just curious: Why isn't it working the recommended way?
And: how to make things in submodules to be importable from topmodule? In apps.py? Or in __init__.py?
You cannot import your models into the root module of your app. That's one of the limitations of Django's application framework. You need to remove the from .models import * line from myapp/__init__.py.
Django first imports the root module of every installed application. This is used to set up the application configs, which are needed to set up relational fields between models in different apps. To set up these relations, both of the relevant apps must've been loaded.
Django learned the hard way that allowing models to be imported at any time greatly complicated this process, and this introduced a range of hard-to-solve bugs. In 1.7 this process was greatly simplified, reducing the number of bugs, but in that simplification it was decided that all applications must've been loaded before any model can be imported.