Import error:No module named app1.models - django

In django, I am trying to populate my database from a csv file. with the help of this tutorial I wrote this code:
load_data.py:
# Full path and name to your csv file
csv_filepathname="Home/Desktop/MyProject/practice/app1/data/link1.csv"
# Full path to your django project directory
your_djangoproject_home="Home/Desktop/MyProject/practice/"
import sys,os
sys.path.append('Home/Desktop/MyProject/practice/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from app1.models import Link
import csv
dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')
for row in dataReader:
abc = Link()
abc.name = row[0]
abc.roll = row[1]
abc.save()
Now, when I run this, I get import error saying no module named app1.models. I can't figure it out. Can someone please highlight the mistakes?
my directory structure
I'm working on python 2.7 and django 1.6.

All package directories in Python need an __init__.py file, which can be empty.
You shouldn't really create app directories yourself anyway; you should have run manage.py startapp app1 which would have done it for you.
(Also, note you should absolutely not be using Django 1.6, which is several years old, unsupported, and almost definitely insecure. Upgrade to a more recent, supported, version.)

Related

Initialising flask environment variable issues

I am trying to create a an application using Flask. I have done this before successfully, however, I am not sure why this is not working this time. Everything seems to be in the right order. I have searched for answers, however, I still can't determine what's going wrong as everything seems logical to me? Yet, it is still going wrong?
ZXM934/
app/
__innit__.py
views.py
venv/
run.py
The following are each files contents:
run.py
# Importing app object which was created in __innit__.py file into app.py
from app import app
if __name__ == "__main__":
app.run()
__innit__.py
# This class will ultimately bring our entire application together.
from flask import Flask
# Creating Flask app.
app = Flask(__name__)
# Importing views file to avoid circular import.
from app import views
view.py
# This class represents the UI of our website.
# Importing app directory. As __innit__.py file is apart of this directory,
# this import treats it as a package.
from app import app
#app.route("/")
def public_home():
return "Homepage"
#app.route("/login")
def login():
return "<h1 style='color: red'>Login</h1>"
I set the environment variables as following within the console:
export FLASK_APP=run.py
export FLASK_ENV=development
I then run the following command:
flask run
The following error occurs:
flask.cli.NoAppException: While importing "run", an ImportError was raised:
Traceback (most recent call last):
File "/Users/zahidmalik-ramzan/Desktop/zxm934/venv/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/Users/zahidmalik-ramzan/Desktop/zxm934/run.py", line 2, in <module>
from app import app
ImportError: cannot import name 'app' from 'app' (unknown location)
I don't understand what I am doing wrong?
Your problem is in the file name __innit__.py.
For python to understand that a folder is an actual package within your project structure you need a special file inside, i.e. __init.py__ ps: no double n.
A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace.
Conclusion: change your __innit.py__ to __init.py__

Access python script from one project to another

Main folder
|-project1
|-project2
I have the above structure for django projects.
When I am in project1 in a script i used os.chdir(to_project2) to project 2
I want to access project2's settings.py and fetch some attributes. Is it possible?
#You need to point your directory.[Ex: project2]
import os
os.chdir(project2 )
cd = os.getcwd()
# print the current directory
print("Current directory:", cwd)
#For Access the Django setting attributes
import django
from django.conf import settings
All of those aforementioned code you may use from one of your python file: something.py

Scrapy project can't find django.core.management

I'm trying to follow the method here to 'Scrapy' data from the web and simultaneously save that data directly to my Django database using Scrapy's item pipeline.
However, when I try to run scrapy crawl spidername, I'm getting the error:
ImportError: No module named django.core.management
At first I thought it was because my Scrapy project was outside of my Django project folder, but even after I moved the whole project into my Django project folder I kept getting the same error. If I open a python shell inside the Scrapy project folder in its new location (inside my Django project folder), import django.core.management works fine. So what's going on?
EDIT: Some additional info: I'm doing this on a Webfaction server, and the path to my Django project is /home/gchorn/webapps/django_app/django_project. I'm using Django version 1.4.1, Scrapy 0.16 and Python2.7. The layout of the Django+Scrapy project is as follows:
django_project/
__init__.py
manage.py
settings.py
urls.py
myproject #folder containing wsgi.py
app1
app2
app3
templates
ScrapyProject/
scrapy.cfg
ScrapyProject/
__init__.py
items.py
pipelines.py
settings.py
spiders/
__init__.py
my_spider.py
Try setting this in your Spider's settings.py:
import os
import sys
sys.path.append('/home/gchorn/webapps/django_app')
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_project.settings'
Then you can import your model classes like:
from django_project.app1.models import some_model

Django ImportError for models.py

(Updating my question with more information.)
My django app is running fine on my dev server.
I have a view that pulls from the database using the below line that works fine:
from myapp.models import MyTable
However, if I add the above 'from/import' to another module (see below structure, it's the module named 'problem_module.py') I'm writing where I want to pull from the sqlite3 database, I get this error.
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'myfolder.settings' (Is it on sys.path?): No module named myfolder.settings
I've read and tried various solutions recommended when people get this error, but I missing something because i'm unable to resolve it.
I'm using Django 1.4 and have the lay-out as recommended.
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
myapp/
__init__.py
models.py
admin.py
views.py
indevelopment/
__init__.py
problem_module.py
I figured out what was happening and why after going through the traceback carefully and looking at the django source code. Here is what happens.
When you run:
python manage.py runserver
the environment variable gets set properly assuming you already changed this small little file or just don't pay attention to it because django 1.4 automatically configures it for you.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
However, because this setting of os.environ is under a:
if __name__ = "__main__"
expression, it only gets run if call that file directly, as you do with:
python manage.py runserver
Otherwise, if you are running a file that needs that environment variable - say testing a module in Eclipse - , the os.environ needs to get set in another place (shell, etc).
All the that I got generally pointed to this but I needed the context.
But as a little adjustment (yes, not a good idea as it couples) on the source code you can also hardcode it in manually in/django/conf/__init__.py
Specifically to see where it happens, the change below works:
# in module: /django/conf/__init__.py
class LazySettings(LazyObject):
def _setup(self):
try:
# Comment out the call to os.environ and hardcode in your app settings
# settings_module = os.environ[ENVIRONMENT_VARIABLE]
# WARNING: bad practice to do this. ;.
settings_module = "myapp.settings"
Have you changed/set DJANGO_SETTINGS_MODULE?
Try export DJANGO_SETTINGS_MODULE=mysite.settings and start your dev server.
modify your manage.py:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
PyCharm sometimes override DJANGO_SETTINGS_MODULE to empty string. Try to debug your manage.py and see if it realy changes after setdefault() call.
If its not either change pycharm settings or use os.environ['DJANGO....']='my_settings'..
or hack files at .idea/. .idea/workspaed.xml contains
env name="DJANGO_SETTINGS_MODULE" value="" in this case

Could not import/No module named Django Error with Apache

I had a small proof of concept set up on a development server on a local machine. I'm now trying to move it over to django on a production server, which I'm using webfaction for. However, now that I'm switched over to apache from the built in django server I get the following:
ViewDoesNotExist: Could not import orgDisplay.views. Error was: No module named orgDisplay.views
But when check my orgDisplay apps folder there is a view.py in it. What am I doing wrong? I've tried adding the following to my settings.py by suggestion of the django IRC room.
import sys
sys.path.append(r"/home/user/webapps/django_project/myproject/orgDisplay")
which is the path to my app.
any ideas on how to even begin to trouble shoot this?
Thanks in advance.
I assume you're using mod_wsgi (which is recommended by Django authors), not mod_python. This is the way you should use your sys.path:
django.wsgi:
import os, sys
sys.path.append(r"/home/user/webapps/django_project/myproject/")
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
sys.stdout = sys.stderr # Prevent crashes upon print
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
urls.py:
from django.conf.urls.defaults import *
urlpatterns = (
("", include("orgDisplay.urls")),
# ...
)
orgDisplay/urls.py:
import views
urlpatterns = (
(r'^some_view/$', views.some_view), # It is actually orgDisplay.views.some_view
# many more records ...
)
It is a bad idea to add project dir itself to path since you're be getting name conflicts between multiple projects.
I think you're appending the wrong directory to sys.path. I think Python is looking in the .../myproject/orgDisplay folder for the orgDisplay package. Try removing the orgDisplay from your string, like this:
import sys
sys.path.append(r"/home/user/webapps/django_project/myproject")
The other option would be to simply add myproject (or whatever your project is actually called) in the import statement.
# instead of "from orgDisplay import views"
from myproject.orgDisplay import views
Also, make sure to restart Apache after every edit.
looking at manage.py, it does it like so:
import sys
from os.path import abspath, dirname, join
from django.core.management import setup_environ
# setup the environment before we start accessing things in the settings.
setup_environ(settings_mod)
sys.path.insert(0, join(PINAX_ROOT, "apps"))
sys.path.insert(0, join(PROJECT_ROOT, "apps"))
Provided your WSGI file is in your project directory, a slightly more flexible way is this:
import os, sys
sys.path.append(os.path.dirname(__file__))
This will enable you to change your project location later without having to modify your WSGI file.