Issue loading admin.site.urls after changing the settings folder - django

I re-organized Django,the following way:
config
- settings
- base.py
- local.py
urls.py
wsgi.py
In base.py/local.py:
ROOT_URLCONF = 'config.urls'
WSGI_APPLICATION = 'config.wsgi.application'
In manage.py I changed:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
In wsgi.py I changed:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
I have the following error on runserver:
\django\contrib\admin\sites.py", line 269, in get_urls
path('%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)),
AttributeError: 'AccountAdmin' object has no attribute 'urls'
It is related to this line:
path('admin/', admin.site.urls), # Django 2.0 syntax
If I comment that line I get the following error:
django\contrib\admin\sites.py", line 79, in check
if modeladmin.model._meta.app_config in app_configs:
AttributeError: 'AccountAdmin' object has no attribute 'model
The app admin is in installed app, I don't know what is creating this issue.

Hmm... Several things happen here. One thing at a time:
Under your settings dir put an __init__.py file with the following contents in it:
from .base import *
try:
from .local import *
LIVE = False
except ImportError:
LIVE = True
if LIVE:
try:
from .production import *
except ImportError:
pass
By putting this inside the __init__.py file, you can reference to your settings file simply with 'config.settings', leaving local or production unreferenced (the __init__.py will handle them).
Now that this is out of way, change both uwsgi.py and manage.py to:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
Assuming that you have done all that, it should work (that's how I structure my projects for years and had never any problems). Otherwise, please update your question with project structure and base.py and local.py contents to work it out.

Related

Wagtail settings only use .dev

I do not understand how to alternate between production and dev settings. Wagtail docs do not cover it and the only wagtail tutorial I can find mentions it and then completely skips over it. There is a settings file:
--| settings
----| __init__.py
----| base.py
----| dev.py
----| production.py
----| .env
my init file:
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
ENV = os.environ.get('AMSS_ENV')
if ENV == 'dev':
from .dev import *
elif ENV == 'prod':
from .production import *
AMSS_ENV is set to 'prod'. I also have the DJANGO_SETTINGS_MODULE variable set to production in the .env from a different attempt. Does the init file not fire first? is my logic broken? I get no errors and everything works but it loads in dev every time. I've tried so many other things and it just sticks like this. Can someone tell me what am I supposed to do? or where I can look?
It is always useful to check wsgi.py and manage.py to see which settings file they are set to. It is very easy to accidentally serve or run commands with the wrong settings file by forgetting about these two files.

django wsgi setup with settings subfolder

I'm trying differents environment settings for my project, below is my project folder structure:
|-app
|-project
|-__init__.py
|-settings
|-__init__.p
|-base.py
|-dev.py
|-prod.py
|-urls.py
|-wsgi.py
In base.py, how can i setup WSGI_APPLICATION django settings variable to point wsgi file on parent folder ?
File wsgi.py:
if base.STATUS == 'DEV':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.dev')
application = get_wsgi_application()
elif base.STATUS == 'PROD':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.prod')
application = Cling(get_wsgi_application())
else:
raise Exception('Settings App Error !')
File base.py:
...
WSGI_APPLICATION = 'project.wsgi.application'
...
File dev:
from project.settings.base import *
ALLOWED_HOSTS = ['127.0.0.1']
DEBUG = TRUE
File prod.py:
from project.settings.base import *
ALLOWED_HOSTS = ['domain']
DEBUG = FALSE
The error is:
django.core.exceptions.ImproperlyConfigured: WSGI application 'project.wsgi.application' could not be loaded; Error importing module.
Thanks in advance.
Your WSGI file is named wsgy.py, but Django expects wsgi.py. Rename the file to wsgi.py.
You need to have an __init__.py file in your project folder to import your project folder as a module. Just make an empty __init__.py file in the project directory.
SOLVED
The differents configuration environments are ok the problem was with a library dependency:
The requirements.py file was:
django-static
instead of:
dj-static
The strange is the error thrown was:
django.core.exceptions.ImproperlyConfigured
instead of:
ModuleNotFoundError

Can I make a folder of forms and views and use an __init__.py file like models and test?

I would like to keep my views and forms separate, just like you can with models. Are you able to make a directory of views and forms, and if so, what goes in the init.py files for each.
Update:
I made my folders, but I keep getting errors. Here's all my code info:
myproject structure (abbreviated):
myproject/
myproject/
name/
forms/
__init__.py
name_form.py
models/
__init__.py
name_model.py
urls.py
views/
__init__.py
name_view.py
models/init.py
from .name_model import Name
models/name_model.py
from django.db import models
from django.urls import reverse
class Name(models.Model):
...
forms/__init__.py and views/__init__.py are blank files.
urls.py
from django.urls import path
from name.views import name_view
app_name = 'name'
urlpatterns = [
path('', views.name_view, name='name-view'),
]
forms/name_form.py
from django.forms import ModelForm, TextInput
from name.models import Name
class NameForm(ModelForm):
class Meta:
model = Name
views/name_view.py
from django.shortcuts import render, redirect
from name.forms import NameForm
def name_view(request):
...
I run python3 manage.py makemigrations in the terminal and get:
/myproject/name/views/name_view.py", line 4, in <module>
from name.forms import NameForm
ImportError: cannot import name 'NameForm'
Thinking you can't make a ModelForm without a model, I run python3 manage.py migrate and get the same error.
I created a project to isolate this issue. Without the folders it worked, unless I messed up my original code trying to get this to work.
Just make a folder for your views and a folder for your forms wherever you want them to be and put an empty __init__.py file into each folder. The purpose of the __init__.py file is to tell python to treat the folder as a module. Then make your views.py file and your forms.py file in their respective directories and now you can do...
from myproject.path.to.views import MyView
from myproject.path.to.forms import MyForm
...as if it were any other module. Which it is.

ImportError After Moving App to Nested Folder

My application was working fine when I wanted to see whether I could organize my project in a better way. I read through this tutorial on structuring a django project.
Before my project structure was as follows:
camucamu
books
admin.py
models.py
views.py
__init__.py
static
templates
urls.py
views.py
settings.py
wsgi.py
__init__.py
What I wanted to do was move the books app into an apps folder. Thus I did that and changed the project structure to the following:
camucamu
apps
books
admin.py
models.py
views.py
__init__.py
static
templates
urls.py
views.py
settings.py
wsgi.py
__init__.py
I then changed the imports in views.py and admin.py
from books.models to apps.books.models.
I also changed INSTALLED_APPS in settings.py from books to apps.books.
When I then tried to run syncdb, I get the following error:
raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
django.core.exceptions.ImproperlyConfigured: ImportError apps.books: No module named apps.books
What am I messing up here so it can't find my app anymore?
Your apps folder does not have an __init__.py file so it cannot be recognized as a python module
I got the same error, following the same guide, as the last point of the following list was not cited. Make sure you performed the following changes:
Create a blank __init__.py file inside the apps folder (needed for python to recognize it as a package)
Update the import statements wherever you refer to an external app:
from projectname.apps.appname.models import YourModel, YourOtherModel
Inside settings.py edit INSTALLED_APPS such that it looks like this:
INSTALLED_APPS = (
...
# apps
'projectname.apps.appname1',
'projectname.apps.appname2',
)
This one is not specified in the guide: In all your urls.py files, update the urlpatterns!
BEFORE:
# client views
urlpatterns += patterns('appname',
...
)
AFTER:
# client views
urlpatterns += patterns('projectname.apps.appname',
...
)
Finally remember to update your changes by calling python manage.py syncdb
Hope that helped.

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