Django - include app urls - python

I have the following structure (Django 1.4):
containing_dir/
myproject/
myapp1/
myapp2/
myapp3/
myproject, myapp1, myapp2, and myapp3 all have init.py, so they're all modules.
In manage.py (under containing_dir) I have os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
in myproject.settings i define:
[..]
ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = (
[..]
'myproject.myapp1',
'myproject.myapp2',
'myproject.myapp3',
)
[..]
In myapp1.urls.py I define:
urlpatterns = patterns('myapp1',
url(r'^agent/$', 'views.agent', name='agent')
)
and I try to import it in myproject.urls I try to import myapp1 urls like this:
(r'^myapp1/', include('myproject.myapp1.urls'))
but whenever I try lo load localhost:8000/myapp1/agent I get
Exception Value: No module named myapp1
I think thrown from withing myapp1.urls
Any help? thanks

You must have a
__init__.py
file inside your "myproject" directory. When you say:
(r'^myapp1/', include('myproject.myapp1.urls'))
you are saying "myproject" (as well as myapp1) is a python packege.

In myproject.settings make following changes :
INSTALLED_APPS = (
[..]
'myapp1',
'myapp2',
'myapp3',
)

Try:
urlpatterns = [
...
url(r'^app_name/', include('app_name.urls', namespace='project_name'))
...
]

Does ROOT_URLCONF need to point to myproject.urls?
If you place your apps inside of myproject you need to use the proper view prefix.
urlpatterns = patterns('myproject.myapp1',
...

To solve this issue just select "myproject" directory in PyCharm and set this as a source root.
Your project don't know from which root it has to search for given app.
It fixed the issue for me.
Thank you.

Recently, In new versions of Django introduces path(route, view, kwargs=None, name=None) instead of old url() regular expression pattern.
You must have __init__.py file in app folders to recognize it as a package by django project i.e myproject
Django project i.e. myproject urls.py file must be updated to include examples like:
path('', include('django_app.urls'))
path('url_extension/', include('django_another_app.urls'))
Above example includes two apps urls in it. One is without adding any extension to path in url and another is with extension to path in current url.
Also, Do not forget to add django apps in INSTALLED_APPS in settings.py file to recognise it as app by django project something like this.
ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = [
...
django_app,
django_another_app
...
]
For more information look at documentation.

Related

Django Project Directory Structure

in my django project structure, i want all my django apps in a separate Apps Folder, but when i include it in settings.py it raises an error,
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'TestApp'. Check that 'Apps.TestApp.apps.TestappConfig.name' is correct.
INSTALLED_APPS = [
...
'Apps.TestApp'
]
But
when i only include TestApp, i raises no module named 'TestApp' Error.
INSTALLED_APPS = [
...
'TestApp'
]
If you are using django version < or = 2 then you should register your app like
INSTALLED_APPS = [
...
'testapp.apps.TestappConfig'
]
the app name should not be in 'UPPER' case otherwise you will get errors.
if you are using django > or = 3 then you can register your app with it's original name too.
You are registering your app in 'Title' style which is not permitted.
You could do the following in your settings.py file:
INSTALLED_APPS = [
... # other necessary apps here
# include your local apps you are creating for your project here
'testapp.apps.app_name', # assuming app_name is one of your apps
'testapp.apps.another_app',
'testapp.apps.third_custom_app'
]
Then in each of your app folders (where your models.py, views.py, urls.py, etc. are) include an apps.py file that follows the following pattern:
from django.apps import AppConfig
class AppNameConfig(AppConfig): # note the formatting of this class name
default_auto_field = "django.db.models.BigAutoField"
name = "apps.app_name" # apps is the name of the directory where all your apps are located.
# app_name is the name of the individual directory within your apps directory where this apps.py file is saved

in Django 1.11.6, settings.py INSTALLED_APPS not find my modules?

This is my Django settings file:
my modules:
apps/users/apps.py
from django.apps import AppConfig
class UserConfig(AppConfig):
name = 'apps.users'
Error I get:
I scanned Django 1.11.6 doc, could not find INSTALLED_APPS change , and I don't know how to resolve this issue?
The reason of write apps.users.apps.UserConfig is that's the direction of the class that contain the name 'apps.users' , to avoid that you can add apps.users inside INSTALLED_APPS or rename name=users, put user inside INSTALLED_APPS, and add this line after BASE_DIR var sys.path.insert(0, os.path.join(BASE_DIR, 'apps')), with this in the future you wont need to include in the imports from apps.user... just from user...

Trouble adding Django-Assets / Webassets directory to look for assets.py files

Was looking for a Python package for Django to manage assets, using Sass to compile CSS, and also cache busting, and Django-Assets / Webassets was recommended. Having trouble getting it setup though with my directory structure.
By default it looks for assets.py in each installed app. I want to set it up so that it sits in the same directory as settings.py and compiles app specific assets from each app directory into /static/js and /static/css.
I have django_assets in INSTALLED_APPS. According to the docs it looks like I needed to add this to settings.py:
ASSETS_MODULES = [
'project_dir',
]
Or:
ASSETS_MODULES = [
os.path.join(BASE_DIR, 'project_dir'),
]
Or:
ASSETS_MODULES = [
PROJECT_ROOT
]
At any rate, it just returns No asset bundles were found. If you are defining assets directly within your template, you want to use the --parse-templates option.
Even moving the assets.py into one of the app directories, it is looking in BASE_DIR/scripts which is where I keep my manage.py. Again, changing ASSETS_ROOT doesn't really same to be doing anything.
~/portal-client
project_dir
apps
account
templates
account
login.html
forms.py
urls.py
views.py
home
templates
home
home.html
urls.py
views.py
results
assets.py
settings.py
urls.py
scripts
manage.py
static
templates
base.html
footer.html
title.html
Couple of quick notes, for ASSETS_MODULES, the key word is additional:
django-assets will automatically look for assets.py files in each application, where you can register your bundles. If you want additional modules to be loaded, you can define this setting. It expects a list of importable modules:
i.e., we only use ASSETS_MODULES if we have assets.py files outside of any application. In your case, we will only specify this if project_dir is not an INSTALLED_APP.
Second, when using ASSETS_MODULES, you specify a dotted module path, not a directory. In your case, this would be project_dir.assets only if project_dir is not already part of INSTALLED_APPS.

ImportError: no module named urls but ROOT_URLCONF is correct

I've read through all the similar questions that I could find on google/SO, and most people had an issue with their ROOT_URLCONF being incorrect or missing an init.py.
My project structure is
djangotut/
polls/
static/
templates/
__init__.py
manage.py
settings.py
urls.py
My project is called djangotut, and there's also a group level called user_myusername_xyz (my place of work has some prefab code we use for project setup, and I've done this many times without running into this problem).
I've tried
ROOT_URLCONF = 'user_myusername_xyz.djangotut.urls'
(this is what our projects' settings.py files default to)
ROOT_URLCONF = 'djangotut.urls'
and
ROOT_URLCONF = 'urls'
I get the ImportError every time, and I know it's that line because the ExceptionValue changes to the string I used there. (ex: "No module named user_myusername_xyz.djangotut.urls").
The urls.py file is there, so why can't settings.py see it?
urls.py
from django.conf.urls import include, patterns, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^apps/username_myusername_xyz/djangotut/',
include('djangotut.polls.urls')),
url(r'^admin/', include('admin.site.urls')),
)
The solution was to remove the quotes from 'admin.site.urls.' The quotes are still needed when including URLs from an INSTALLED_APP, but for some reason the admin one doesn't like quotes.
is user_myusername_xyz a python package? Does that directory have an
init.py
? If it doesn't, it shouldn't be in an import path
I'm guessing no, it doesn't, and you need something more like:
ROOT_URLCONF = 'djangotut.urls'

why django app not load static files when debug false? [duplicate]

Am building an app using Django as my workhorse. All has been well so far - specified db settings, configured static directories, urls, views etc. But trouble started sneaking in the moment I wanted to render my own beautiful and custom 404.html and 500.html pages.
I read the docs on custom error handling, and set necessary configurations in UrlsConf, created corresponding views and added the 404.html and the 500.html to my app's template directory (specified in the settings.py too).
But the docs say you can actually view custom error views until Debug is Off, so I did turn it off to test my stuff, and that's when stuff goes berserk!
Not only do I fail to view the custom 404.html (actually, it loads, but because my error pages each contain a graphic error message -as some nice image), the source of the error page loads, but nothing else loads! Not even linked CSS or Javascript!
Generally, once I set DEBUG = False, all views will load, but any linked content (CSS, Javascript, Images, etc) wont load! What's happening? Is there something am missing, concerning static files and the DEBUG setting?
If you still need to server static locally (e.g. for testing without debug) you can run devserver in insecure mode:
manage.py runserver --insecure
With debug turned off Django won't handle static files for you any more - your production web server (Apache or something) should take care of that.
In urls.py I added this line:
from django.views.static import serve
add those two urls in urlpatterns:
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
and both static and media files were accesible when DEBUG=FALSE.
You can use WhiteNoise to serve static files in production.
Install:
pip install WhiteNoise==2.0.6
And change your wsgi.py file to this:
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
And you're good to go!
Credit to Handlebar Creative Blog.
BUT, it's really not recommended serving static files this way in production. Your production web server(like nginx) should take care of that.
Johnny's answer is great, but still didn't work for me just by adding those lines described there. Based on that answer, the steps that actually worked for me where:
Install WhiteNoise as described:
pip install WhiteNoise
Create the STATIC_ROOT variable and add WhiteNoise to your MIDDLEWARE variable in settings.py:
#settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', #add whitenoise
'django.contrib.sessions.middleware.SessionMiddleware',
...
]
#...
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root
Then, modify your wsgi.py file as explained in Johnny's answer:
#wsgi.py
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
After that, deploy your changes to your server (with git or whatever you use).
Finally, run the collectstatic option from your manage.py on your server. This will copy all files from your static folders into the STATIC_ROOT directory we specified before:
$ python manage.py collectstatic
You will now see a new folder named staticfiles that contains such elements.
After following these steps you can now run your server and will be able to see your static files while in Production mode.
Update: In case you had version < 4 the changelog indicates that it's no longer necessary to declare the WSGI_APPLICATION = 'projectName.wsgi.application' on your settings.py file.
If you are using the static serve view in development, you have to have DEBUG = True :
Warning
This will only work if DEBUG is True.
That's because this view is grossly
inefficient and probably insecure.
This is only intended for local
development, and should never be used
in production.
Docs: serving static files in developent
Updated link, and this
EDIT: You could add some urls just to test your 404 and 500 templates, just use the generic view direct_to_template in your urls.
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
('^404testing/$', direct_to_template, {'template': '404.html'})
)
You actually can serve static files in a production Django app, securely and without DEBUG=True.
Rather than using Django itself, use dj_static in your WSGI file (github):
requirements.txt:
...
dj-static==0.0.6
YOURAPP/settings.py:
...
STATIC_ROOT = 'staticdir'
STATIC_URL = '/staticpath/'
YOURAPP/wsgi.py:
...
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
You can debug this in many different ways. Here's my approach.
localsettings.py:
DEBUG = False
DEBUG404 = True
urls.py:
from django.conf import settings
import os
if settings.DEBUG404:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
)
Be sure to read the docs ;)
https://docs.djangoproject.com/en/2.0/howto/static-files/#limiting-use-to-debug-true
Ultimate solution:-
So basically when you make debug = False, Django doesn't want to take care of your static files.
So we want something that can take care of our files.
The answer is whitenoise.
pip install whitenoise in your environment
Add 'whitenoise.middleware.WhiteNoiseMiddleware' in your middleware list in settings.py.
This should be added just below the 'django.middleware.security.SecurityMiddleware' and above all the remaining middleware. So that your middleware list will look like this:-
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# add it exactlyhere
'django.contrib.sessions.middleware.SessionMiddleware',
'...'
]
Add 'whitenoise.runserver_nostatic' on top of your installed apps
So that your installed apps list will look like this:-
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'django.contrib.admin',
'django.contrib.auth',
'...'
]
Done, you will be able to serve static files in production now!!
From here I took help by mixing a few answers. Here, I am adding my whole parts. [I am doing this for a beginners help and for my future use as well]
Well at first the question is why Debug=False needed!
I put my project in AWS and it was being connection timeout after few hours because of memory leaking.
At first I thought for celery. [of course I am just a beginner]
Then I put DEBUG=False from DEBUG=True As we can see the security warning in settings.py
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
Once I did that my staticfiles were not loading successfully in webpages.
Then I searched everywhere and at first tried from here the --insecure command to runserver.
python manage.py runserver --insecure
Which is successful but I don't want the insecure mode in my project when it is in production.
And as the proper solution [according to me] I followed the steps below.
At first, I correct the static URL,root, and dir in settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
Then collect the static files by command
python manage.py collectstatic
Now the second step, [which also provided here]
At first install whitenoise in your project directory in the command line
pip install whitenoise
Then Add 'whitenoise.middleware.WhiteNoiseMiddleware' in your middleware list in settings.py.
This should be added just below the 'django.middleware.security.SecurityMiddleware' and above all the remaining middleware. So that your middleware list will look like this:-
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware', #after this line
'whitenoise.middleware.WhiteNoiseMiddleware', #add it exactlyhere
'django.contrib.sessions.middleware.SessionMiddleware', #before this
'...'
]
Add 'whitenoise.runserver_nostatic' on top of your installed apps So that your installed apps list will look like this:-
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'django.contrib.admin',
'django.contrib.auth',
'...'
]
Done, you will be able to serve static files in production now!! [I did on my local environment as well]
Just use the runserver command as always no insecure or anything needed.
python manage.py runserver
Boom!!! It's working for me.
Hahaha. I know kinda childish nature but I am so happy now.
Thanks to everyone who provided answers here and help my work.
This is Exactly you must type on terminal to run your project without DEBUG = TRUE
and then you see all assets (static) file is loading correctly On local server .
python manage.py runserver --insecure
--insecure : it means you can run server without security mode
For last versions of Django please look at the answer here: https://stackoverflow.com/a/7639983/6180987
For django version below 1.10 the solution should work:
Just open your project urls.py, then find this if statement.
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )
You can change settings.DEBUG on True and it will work always. But if your project is a something serious then you should to think about other solutions mentioned above.
if True:
urlpatterns += patterns(
'django.views.static',
(r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )
In django 1.10 you can write so:
urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT }), ]
when i make DEBUG = True my static are doesn't work.
if i run my project in python manage.py runserver --insecure . By this i got my static as well.
Solution 1:
python manage.py runserver --insecure
Solution 2:
But I Need Permanent Solution. then i install pip install dj-static==0.0.6 and add some code to my wsgi.py file:
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
and then i added some in setting.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
STATICFILES_DIRS = [
BASE_DIR / "static",
]
I agree with Marek Sapkota answer; But you can still use django URFConf to reallocate the url, if static file is requested.
Step 1: Define a STATIC_ROOT path in settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
Step 2: Then collect the static files
$ python manage.py collectstatic
Step 3: Now define your URLConf that if static is in the beginning of url, access files from the static folder staticfiles. NOTE: This is your project's urls.py file:
from django.urls import re_path
from django.views.static import serve
urlpattern += [
re_path(r'^static/(?:.*)$', serve, {'document_root': settings.STATIC_ROOT, })
]
I got this problem today and this fixed it while on development, If you still need to server static locally (e.g. for testing without debug) you can run devserver in insecure mode:
manage.py runserver --insecure
Don't worry because when in production, this hosting platform (Apache, Heroku E.T.C ) would handle serving the static files for you.
Note: Heroku Doesn't server static files, you'd want to put it on AWS or MS Azure
nginx,settings and url configs
If you're on linux this may help.
nginx file
your_machn:/#vim etc/nginx/sites-available/nginxfile
server {
server_name xyz.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /var/www/your_prj;
}
location /media/ {
root /var/www/your_prj;
}
...........
......
}
urls.py
.........
.....
urlpatterns = [
path('admin/', admin.site.urls),
path('test/', test_viewset.TestServer_View.as_view()),
path('api/private/', include(router_admin.urls)),
path('api/public/', include(router_public.urls)),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
.....
........
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
.....
....
Ensure to run:
(venv)yourPrj$ ./manage.py collectstatic
yourSys# systemctrl daemon-reload
This is normal and intended behavior.
Warning
This will only work if DEBUG is True.
you can actually view custom error views until Debug is Off
If Django is just reading from the filesystem and sending out a file, then it has no advantage over a normal web server, all web servers are capable to server the files on it's own.
Furthermore, if you serve static files with Django, you will keep the Python process busy for the duration of the request and it will be unable to serve the dynamic requests to which it is more suited.
For these reasons, the Django static view is designed only for use during development and will not work if your DEBUG setting is False.
Since during development we only usually have one person accessing the site at a time (the
developer), Django is fine to serve static files.
Support for string view arguments to url() is deprecated and will be removed in Django 1.10
My solution is just small correction to Conrado solution above.
from django.conf import settings
import os
from django.views.static import serve as staticserve
if settings.DEBUG404:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', staticserve,
{'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
)
I did the following changes to my project/urls.py and it worked for me
Add this line :
from django.conf.urls import url
and add :
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }),
in urlpatterns.
Although it's not safest, but you can change in the source code. navigate to Python/2.7/site-packages/django/conf/urls/static.py
Then edit like following:
if settings.DEBUG or (prefix and '://' in prefix):
So then if settings.debug==False it won't effect on the code, also after running try python manage.py runserver --runserver to run static files.
NOTE: Information should only be used for testing only

Categories