I've been googling this all day and have not come across a solution, hope you can help:
Using Django 1.6, I made an app called "builds" as part of a project called "computerbuilder".
The site works fine when I use the test server, however I created a file to populate the database with some items, and it's giving me the error when I run python fillDB.py:
Traceback (most recent call last):
File "fillDB.py", line 1, in <module>
from builds.models import BuildsTable
ImportError: No module named builds.models
This is my file fillDB.py:
from builds.models import BuildsTable
moboDB = open("db.txt", "r")
lines = moboDB.read().split('\",')
print lines
def main():
global lines
global BuildsTable
for item in lines:
mobo = BuildsTable.objects.get(moboListing="%s" % item[0])
price_local = BuildsTable.objects.get(moboListing="%s" % item[1])
if(BuildsTable.objects.filter(
moboListing = mobo, price = price_local).exists() == False):
mydb = BuildsTable(moboListing = mobo, price = price_local)
mydb.save()
main()
This is my models.py file from the "builds" app I made:
from django.db import models
# Create your models here.
class BuildsTable(models.Model):
id = models.AutoField(primary_key=True)
moboListing = models.CharField(max_length=200)
price = models.IntegerField()
My directory looks like this:
├── builds
│ ├── admin.py
│ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── computerbuilder
│ ├── dev
│ │ ├── db.txt
│ │ ├── fillDB.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── views.py
│ ├── wsgi.py
├── manage.py
└── requirements.txt
Since I'm using an external file not part of Django, I think that's why its having trouble recognizing it. Also using postgres if that helps.
You need to add the init.py in dev folder. Because it treated as a python package. Next you need to add your django project path in fillDB.py like this,
Root
├──├── builds
│ ├── admin.py
│ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── computerbuilder
│ ├── dev
│ │ ├── db.txt
│ │ ├── fillDB.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── views.py
│ ├── wsgi.py
├── manage.py
└── requirements.txt
Follow the above folder structure,
And also you need to set the django environment variable to this file.
fillDB.py
import sys
import os
if __name__ == "__main__":
sys.path.append('/path/Root')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "computerbuilder.settings")
from builds.models import BuildsTable
mobo = BuildsTable.objects.all()
print mobo
Hope this help you
Check you sys.path to see whether there have you path or not. Every time you run your python project, python will append you current path to the sys.path. And once you quit the python enviroment, python will remove the path you appended in.
Your problem is you run just run fillDB.py, python just append '../computerbuilder/dev' into sys.path, so python can not find builds module.
The solution is move your fillDB.py file to the same level as builds folder
├── builds
├── fillDB.py
│ ├── admin.py
│ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── computerbuilder
│ ├── dev
│ │ ├── db.txt
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── views.py
│ ├── wsgi.py
├── manage.py
└── requirements.txt
Hope it can help you :D
Related
SOS. I'm in the process of migrating my SQLite database to MySQL and I'd like to share my MySQL connection using a function in /db/connect.py with my app at /app/app.py. I'm using a temp file to test the connection at /app/test.py which contains the function import. The connection from /db/connect.py runs successfully by itself. However, even after following other guides to the letter, my function in /db/connect.py isn't importing correctly. Even after adding an empty __init__.py file in the /db/ directory.
What I've tried
Here's a small sampling of what I've tried here, here, here, and here (as well as all other questions in stack overflow on the topic, e.g., here, here, here, here, etc).
/db/test.py (temp file with function import)
Imports /db/connect.py > sql_db_connection().
from db.connect import sql_db_connection
import db
def get_all():
conn = sql_db_connection()
cursor = conn.cursor()
cursor.execute("select * from posts")
result = cursor.fetchall()
for x in result:
print(x)
Error (error from running test.py)
Traceback (most recent call last):
File "/Users/<uname>/<my-long-app-name>/app/test.py", line 1, in <module>
from db.connect import sql_db_connection
ModuleNotFoundError: No module named 'db'
/db/connect.py (function for mysql connection)
import sshtunnel
import MySQLdb
import os
from dotenv import load_dotenv
# Load all env vars
load_dotenv()
def sql_db_connection():
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username=os.getenv("REMOTE_DB_SSH_USERNAME"), ssh_password=os.getenv("REMOTE_SSH_PASSWORD"),
remote_bind_address=(
os.getenv("REMOTE_BIND_ADDRESS"), 3306)
) as tunnel:
conn = MySQLdb.connect(
user=os.getenv("REMOTE_DB_SSH_USERNAME"),
passwd=os.getenv("REMOTE_DB_PASSWORD"),
host='0.0.0.0', port=tunnel.local_bind_port,
db=os.getenv("REMOTE_DB_NAME"),
)
print('Connected!')
return conn
sql_db_connection()
Tree
.
├── Dockerfile
├── README.md
├── __pycache__
│ ├── app.cpython-310.pyc
│ ├── app.cpython-39.pyc
│ ├── config.cpython-39.pyc
│ ├── wsgi.cpython-38.pyc
│ └── wsgi.cpython-39.pyc
├── app
│ ├── Dockerfile
│ ├── __init__.py
│ ├── __pycache__
│ ├── app.py
│ ├── config.py
│ ├── public
│ ├── requirements.txt
│ ├── templates
│ ├── test.py
│ └── wsgi.py
├── db
│ ├── Dockerfile
│ ├── README.md
│ ├── __init__.py
│ ├── __pycache__
│ ├── connect.py
│ ├── database.db
│ ├── dump.sql
│ ├── init_db.py
│ ├── mysql_dump.sql
│ ├── schema.sql
│ └── schema_mysql.sql
├── docker-compose.yml
├── features.md
├── images
├── requirements.txt
├── setup.py
├── venv
│ ├── bin
│ ├── include
│ ├── lib
│ ├── man
│ └── pyvenv.cfg
└── wsgi.py
add these two lines as the first two lines in test.py
import sys
sys.path.append('/Users/<uname>/<my-long-app-name>')
This is my project structure:
.
├── connectapp
│ ├── __init__.py
│ ├── __pycache__
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── djangoproject
│ ├── __init__.py
│ ├── __pycache__
│ ├── asgi.py
│ ├── djangoproject.sqlite3
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── djangoproject.sqlite3
├── hackerapp
│ ├── Controllers
│ ├── Models
│ ├── Serializers
│ ├── __init__.py
│ ├── __pycache__
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ └── tests.py
├── manage.py
└── requirments.txt
When I do below being in top level folder:
python3 manage.py migrate hackerapp
I am getting this:
djangoproject/djangoproject/urls.py", line 19, in <module>
from ..hackerapp.Controllers import PersonViewSet, DepartmentViewSet
ImportError: attempted relative import beyond top-level package
To me looks import should work but it's not, can someone tell me why?
I guess (?) migrate hackerapp are cli params to the manage.py script. The error means that the top level folder is not a package. To make it into a package add an (empty) __init__.py file then from that folder run:
python -m manage migrate hackerapp # note no .py
I suspect that I am not understanding something about django. I am trying to test the file scrape.py which calls an api and parses then writes the response to the model CMC in the models.py using sqlalchemy. I am trying to test it to see if the file itself will run but (here's where I think I'm going wrong) I am pressing the play button while having the scrape.py file pulled up in vscode. I suspect there is something here that Django won't allow but am not familiar enough with django to know if that is the case. It is throwing a ModuleNotFound error as described below but I suspect that it's doing that because I am calling it because when I type the dot after apis after import at the top of the file it shows a list of all the drop-down files in my apis app.
Here is my project tree:
(base) justinbenfit#MacBook-Pro-3 cds_website % tree
.
├── api
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-38.pyc
│ │ ├── admin.cpython-38.pyc
│ │ ├── apps.cpython-38.pyc
│ │ ├── models.cpython-38.pyc
│ │ ├── serializers.cpython-38.pyc
│ │ ├── urls.cpython-38.pyc
│ │ └── views.cpython-38.pyc
│ ├── admin.py
│ ├── apps.py
│ ├── main.py
│ ├── management
│ │ ├── __init__.py
│ │ ├── commands
│ │ │ ├── __init__.py
│ │ │ ├── __pycache__
│ │ │ │ └── private.cpython-39.pyc
│ │ │ ├── private.py
│ │ │ └── scrape.py
│ │ └── test.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ │ └── __pycache__
│ │ ├── 0001_initial.cpython-38.pyc
│ │ └── __init__.cpython-38.pyc
│ ├── models.py
│ ├── serializers.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── cds_website
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-38.pyc
│ │ ├── settings.cpython-38.pyc
│ │ ├── urls.cpython-38.pyc
│ │ └── wsgi.cpython-38.pyc
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── requirements.txt
api is an app in a greater project called cds_website. The settings.py file in cds_website project directory contains the following installed apps:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api.apps.ApiConfig',
'rest_framework',
'environ'
]
and my apps.py file in the api app contains the following class:
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = 'api'
CMC is a model in my models.py file. I am trying to import it into scrape.py. I have tried:
from ...models import CMC
from api.models import CMC
from ... import CMC
first one throws: ImportError: attempted relative import with no known parent package second one throws: ModuleNotFoundError: No module named 'api' third one throws: ImportError: attempted relative import with no known parent package
Here is a link to the code repo: https://github.com/Justinbenfit23/cds_website
Everything I have read indicates that at least one of these should work. Any direction appreciated!
I'm teste your project with from api.models import CMC and it's worked
The easiest way is to create ecrape_manage.py in cds_website-master
folder, content of ecrape_manage.py:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cds_website.settings")
import django
django.setup()
exec(open("api/management/commands/scrape.py").read())
and just run with python ecrape_manage.py
I am somewhat still unfamiliar with Django so please excuse the possible elementary question.
am trying to deploy a Django project, but I am having some problems with it.
The project works exactly as it should on Windows, however I am getting this error on my Ubuntu VPS:
Unhandled exception in thread started by <function wrapper at [...]>
Traceback (most recent call last):
[...]
Stack trace from system/django files
File "/home/django/[Project Name]/apps/sale/admin.py", line 8, in <module>
from .forms import SaleRequestFormAdmin
File "/home/django/[Project Name]/apps/sale/forms.py", line 6, in <module>
from apps.listing.models import Listing
ImportError: No module named listing.models
My structure for the project is like this (with irrelevant components removed or shortened):
.
├── apps
│ ├── [...]
│ ├── listing
│ │ ├── admin.py
│ │ ├── api.py
│ │ ├── apps.py
│ │ ├── forms.py
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ ├── [...]
│ │ ├── models.py
│ │ ├── tests.py
│ │ └── views.py
│ ├── sale
│ │ ├── admin.py
│ │ ├── api.py
│ │ ├── apps.py
│ │ ├── forms.py
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ ├── [...]
│ │ ├── models.py
│ │ ├── tests.py
│ │ └── views.py
├── __init__.py
├── [Project Name]
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
The apps folder contains all of my Django apps, and is in the same folder as manage.py and my project folder.
You can see that there is a file called models.py in the listing app.
Does anyone have any idea why this does not work on Linux? I couldn't find any relevant information on Google, and I really don't know why it is failing.
Any help would be greatly appreciated.
I think the problem is that apps path is not in your sys path
Try adding the following in your settings.py file:
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))
Let know if it helps!
I´m trying to deploy my django 1.6.4 project on pythonAnywhere using python 2.7
I already configured a virtual enviroment and the wsgi file according to the guidelines on the website. But I´m getting a 404 when I check the site. The error lol tells me this:
ImportError: Could not import settings 'tango_with_django_project.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named tango_with_django_project.settings
Here´s my wsgi:
# +++++++++++ DJANGO +++++++++++
# TURN ON THE VIRTUAL ENVIRONMENT FOR YOUR APPLICATION
activate_this = '/home/pjestrada/.virtualenvs/rango/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
# To use your own django app use code like this:
import os
import sys
#
## assuming your django settings file is at '/home/pjestrada/mysite/settings.py'
path = '/home/pjestrada/rango/tango_with_django_project'
if path not in sys.path:
sys.path.append(path)
os.chdir(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tango_with_django_project.settings'
#
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
My tree:
├── Dropbox
│ ├── README.txt
│ └── __init__.py
├── README.txt
└── rango
├── LICENSE
├── README.md
└── tango_with_django_project
├── manage.py
├── media
│ ├── profile_images
│ │ └── 10411981_634016890008979_1609187547738555774_n.jpg
│ └── rango2.jpg
├── populate_rango.py
├── rango
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── admin.py
│ ├── admin.pyc
│ ├── bing_search.py
│ ├── bing_search.pyc
│ ├── forms.py
│ ├── forms.pyc
│ ├── models.py
│ ├── models.pyc
│ ├── tests.py
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
├── static
│ ├── about.jpg
│ ├── css
│ │ ├── bootstrap-fluid-adj.css
│ │ ├── bootstrap-responsive.css
│ │ ├── bootstrap-responsive.min.css
│ │ ├── bootstrap.css
│ │ └── bootstrap.min.css
│ ├── img
│ │ ├── glyphicons-halflings-white.png
│ │ └── glyphicons-halflings.png
│ ├── js
│ │ ├── bootstrap.js
│ │ ├── bootstrap.min.js
│ │ ├── jquery-2.1.1.js
│ │ └── rango-ajax.js
│ └── rango.jpg
├── tango_with_django_project
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── settings.py
│ ├── settings.pyc
│ ├── urls.py
│ ├── urls.pyc
│ └── wsgi.py
└── templates
└── rango
├── about.html
├── add_category.html
├── add_page.html
├── base.html
├── category.html
├── category_list.html
├── index.html
├── login.html
├── page_list.html
├── profile.html
├── register.html
├── restricted.html
└── search.html
Try changing value of path.
path = '/home/pjestrada/rango'
That path is your project directory. It worked for me.