I'm wondering if someone can help me. I am looking to restructure a new django project, to represent the below:
-repository/
-config/
-asgi.py
-settings.py
-urls.py
-wsgi.py
-__init__.py
-project root/
-app_1/
-admin.py
-apps.py
-models.py
-tests.py
-urls.py
-views.py
-__init__.py
-app_2/
-...
-app_3/
-...
-migrations/
-__init__.py
-static/
-templates/
-docs/
-manage.py
I have tried to implement this so far by appending the below lines to the settings.py file:
# This is the <repository root>
BASE_DIR = Path(__file__).resolve().parent.parent
# This is the <project repository>
PROJECT_ROOT = BASE_DIR / 'project'
MEDIA_ROOT = PROJECT_ROOT / 'media'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_ROOT = PROJECT_ROOT / 'static_root'
STATIC_URL = PROJECT_ROOT / 'static'
ROOT_URLCONF = 'config.urls'
Templates = [{ ...
'DIRS': [PROJECT_ROOT / 'templates'],
... }]
In the installed apps I have to specify '.app1' vs traditionally just 'app1'. I amended the manage.py,wsgi.py,asgi.py file etc to point to the settings file.
However...
When I try to include() an app specific urlconf in the config root urlconf using the below:
from django.contrib import admin
from django.urls import path, include
import project.app1
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls', namespace='app1'))
]
it says
"ModuleNotFoundError: No module named 'app1'"
Please can someone advise if i am missing a step in this restructue and/or if i'm missing something in the url conf?
You add some subdirectory (project_root) to your app without add __init__.py. Django can't found your app1 path.
Try to register subdirectory to your Django path in settings.py
import sys
sys.path.append(os.path.join(BASE_DIR, 'project_root'))
Suggestion: Do not use whitespace to your Django module/directory
Add app1 in your INSTALLED_APPS in settings.py
Related
I tried uploading staticfiles:
aws:elasticbeanstalk:enviroment:proxy:staticfiles:
/static: /static
got this error in
2022-04-27 03:34:07 ERROR "option_settings" in one of the configuration files failed validation. More details to follow.
2022-04-27 03:34:07 ERROR Invalid option specification (Namespace: 'aws:elasticbeanstalk:enviroment:proxy:staticfiles', OptionName: '/static'): Unknown configuration setting.
2022-04-27 03:34:07 ERROR Failed to deploy application.
ERROR: ServiceError - Failed to deploy application.
I also tried only doing
python manage.py collectstatic
and it did not work
I tried my settings.py in this way:
STATIC_URL = '/static/'
STATIC_ROOT = 'static'
and this way(current way im utilizing):
STATIC_URL = '/static/'
STATIC_ROOT = 'static'
STATICFILES_DIRS = [BASE_DIR / 'templates/static']
You can try following configuration which worked for me.
settings.py
DEBUG = False
STATIC_URL = '/static/'
STATIC_ROOT = 'static'
Run python manage.py collect static
Go to your root urls.py and add
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
...
...
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]
you can refer Github
I am learning Django, and am trying to load a static css file.
I have seen the other questions and read the docs, but I am still unable to see the problem.
I am using Django 1.11.
Here is my urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
My settings.py (only the part to do with static files):
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "/static/")
STATICFILES_DIRS = (
STATIC_ROOT,
)
And the part of my template where I try and load the files:
{% load static %}
Whenever I load the index.html template, the following error messages are displayed by my console:
core.js:5 Uncaught ReferenceError: define is not defined
at core.js:5
localhost/:12 GET http://localhost:8000/static/css/homepage.css
localhost/:11 GET http://localhost:8000/static/css/horz-navbar.css
localhost/:10 GET http://localhost:8000/static/css/fonts.css
localhost/:13 GET http://localhost:8000/static/css/style.css
Here is the file directory structure:
mysite
db.sqlite3
manage.py
mysite
__init__.py
settings.py
urls.py
views.py
wsgi.py
static
admin
css
fonts.css
horz-navbar.css
homepage.css
style.css
templates
index.html
So Django doesn't seem to recognize that the files exist, I have checked and made sure that the files exist on my computer, and I'm not sure if this was needed, but I have also run python manage.py collectstatic
Please tell me if you need anymore information.
Change your STATIC_ROOT into another name and then update your STATICFILES_DIR. Something like this:
STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Replace "{% static "css/fonts.css" %}" with "{% static 'css/fonts.css' %}". There's a mismatch between quotations.
This is my project tree:
projectname
projectname
init.py
settings.py
urls.py
wsgi.py
appname
init.py
admin.py
models.py
test.py
views.py
urls.py
templates
base.html
login.html
Now in the settings.py I am using this code:
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "projectname", "templates"),
)
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "projectname", "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "projectname", "static", "media")
How can I get the path of the project directory, so that I don't need to type the project name projectname in the code and use that code in any other django project?
Update
Or can I just use this
BASE_DIR+'/templates'
BASE_DIR+'/static/media'
Or is it a bad idea?
I would suggest you to use os.path.abspath:
# Project root is intended to be used when building paths,
# e.g. ``os.path.join(PROJECT_ROOT, 'relative/path')``.
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
# Absolute path to the directory where ``collectstatic``
# will collect static files for deployment.
#
# For more information on ``STATIC_ROOT``, visit
# https://docs.djangoproject.com/en/1.8/ref/settings/#static-root
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
# Absolute path to the directory that will hold uploaded files.
#
# For more information on ``MEDIA_ROOT``, visit
# https://docs.djangoproject.com/en/1.8/ref/settings/#media-root
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'uploads/')
BASE_DIR already includes "projectname". When you do os.path.dirname(BASE_DIR), you go up a level from projectname; only to add it back in. Don't do that.
Instead, just use BASE_DIR directly:
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, "templates"),
)
I have a django application that sends off an email containing image files as MIME attachments. The emails are sent from views.py, but in order to attach the files, I need to get the full path name of the image(s), so python can open them. These files are in the static folder in my app, but I can't seem to find a way that I can get the full path of the file on the filesystem that works in development mode - It works fine in production after collecting static, but in dev, it can't find the file as the static files are served from individual app folders in development.
Use finders-module of Django
from django.contrib.staticfiles import finders
result = finders.find('css/base.css')
searched_locations = finders.searched_locations
String result is the file-system path, and if not found, double check searched_locations
project_dir.url add to the end of file
if DEBUG:
urlpatterns += patterns(
'',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': STATIC_ROOT}),
)
project_dir.settings
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static_debug')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
make dirs media & static_debug (add them to .gitignore)
project_dir/
static/
image.jpg
settings.py
urls.py
apps/
__init__.py
some_app/
static/
some_app/
css/
style.css
media/
static_debug/
Now you can run project or directly
python manage.py collectstatic
access from views
from django.templatetags.static import static
static('image.jpg')
static('some_app/css/style.css')
access from templates
{% load staticfiles %}
{% static 'image.jpg' %}
{% static 'some_app/css/style.css' %}
After doing lots of mistakes the following thing worked for me..
Suppose you have following directory structure (Thanks #madzohan)
project_dir/
static/
image.jpg
settings.py
urls.py
apps/
__init__.py
some_app/
static/
some_app/
css/
style.css
And now if you want to get the path of project_dir/static/image.py then
In your project_dir/settings.py file define a STATIC_DIR varaible on the file scope like. ( If not done before )
project_dir/settings.py
import os
# after your other file variables
STATIC_DIR = os.path.join(BASE_DIR, 'static')
Now in your app_name/views.py file from where you want to acess the /static/image.jpg file
app_name/views.py
import os
from project_dir.settings import STATIC_DIR
# here I want the /static/image.jpg file then
image = os.path.join(STATIC_DIR, 'image.jpg')
And then you can have acces to image.jpg file throught image variable
Hope this works well for you
Since you want an app's static, here's what you need!
from django.contrib.staticfiles import finders
APP_LABEL = 'app_youre_looking_at'
FILE_NAME = 'file_name_you_want_to_read_or_write.ext'
stores = finders.AppDirectoriesFinder(app_names={APP_LABEL}).storages
print(f'Here it is: {stores[APP_LABEL].path(FILE_NAME)}')
The FILE_NAME is not required to exist. You can use stores[APP_LABEL].path('') to get path only.
I have a Django project, let's say "project1".
Typical folder structure for applications is:
/project1/
/app1/
/app2/
...
__init__.py
manage.py
settings.py
urls.py
What should I do if I want to hold all of my applications in some separate folder, 'apps' for example? So that structure should look like the following:
/project/
apps/
app1/
app2/
...
__init__.py
manage.py
settings.py
urls.py
You can add your apps folder to your python path by inserting the following in your settings.py:
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))
Then you can use all the apps in this folder just in the same way as they were in your project root!
You can do this very easily, but you need to change the settings.py to look like this:
INSTALLED_APPS = (
'apps.app1',
'apps.app2',
# ...
)
And your urls.py to look like this:
urlpatterns = patterns('',
(r'^app1/',include('apps.app1')),
(r'^app2/',include('apps.app2')),
)
.. and modify any imports to point to the app location
How about you utilize the BASE_DIR variable already present in the settings.py.
Just add the following:
import sys
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
Hope this helps.
As a slight variant to Berhard Vallant's or Anshuman's answers, here is an alternative snippet to place in settings.py
import os
import sys # Insert this line
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Insert the two lines below
APPS_DIR = os.path.join(BASE_DIR, '<your_project_dir_name>/apps/')
sys.path.insert(0, APPS_DIR)
Doing it in this way has the added benefit that your template directories are cleaner as they will look like below. Without the APPS_DIR variable, there will be a lot of repitition of <your_project_dir_name>/apps/ within the DIRS list of the TEMPLATES list.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(APPS_DIR, '<app_name>/templates/<app_name>'),
os.path.join(APPS_DIR, '<app_name>/templates/<app_name>'),
...
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
You can list the apps within the INSTALLED_APPS list as normal with either the short-form name given in apps.py or by using the long-form syntax of appname.apps.AppnameConfig replacing appname with your app's name.
It's easy and simple you need to add to settings.py
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))
and edit your app config for example
old app config:
class MyappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'myapp'
to new app config:
class MyappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
label='myapp'
name = 'apps.myapp'
than installed apps example:
INSTALLED_APPS = [
...
'apps.myapp.apps.MyappConfig'
...
]
I think it's very usefull and helpfull.Good luck :)
Just add __init__.py (4 underscores in total) in your apps folder. Now you can just do
urlpatterns = [
path('polls/',include('apps.polls.urls')),
path('admin/', admin.site.urls)
]
If you're using virtualenv/virtualenvwrapper (which is a bit dated but still valid), you can use the included add2virtualenv command to augment your python path:
mkdir apps
cd apps
pwd
[/path/to/apps/dir]
Copy that path to clipboard, then:
add2virtualenv /path/to/apps/dir
In my case, my project folder structure is the following:
/project/
/apps/
/app1/
/app2/
/src/
/settings.py
...
So I've solved it with these two lines on my settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(BASE_DIR, '../apps'))
No need to alter urls.py.
By using manage.py
# Fisrt create apps folder and appname subfolder
mkdir -p ./apps/<appname>
# Then create new app
python manage.py <appname> ./apps/<appname>