Django - urlpatterns cannot find a module - django

I'm new to Django and from ASP.NET MVC. I just want to make a folder structure something below, though, if I navigate to http://localhost:8000/community_web/, that gives me an error saying "Could not import community_web.controllers.home. Error was: No module named controllers.home".
Folder structure what I want.
<project>
urls.py
<community_web>
urls.py
<controllers>
home.py
I've added the following codes.
To project.urls.py
urlpatterns = patterns('',
(r'^community_web/', include('community_web.urls')),
)
To project.community_web.urls.py
urlpatterns = patterns('',
(r'^$', 'community_web.controllers.home.index'),
)
I thought a views.py would correspond to a controller in ASP.NET MVC term and so I don't want to put all request handlers into one file. If I moved the home.py to its parent folder, it works fine, but without a hierarchical folder structure, creating lots of files in one folder is not my preference. How can I achieve this? or maybe not a good practice in Django?
Thanks in advance,
Yoo

Try popping a __init__.py into the directory controllers. This will make the directory a module python can see.

It is typically not good practice to do it that way. But do what you feel comfortable with. Under controllers do you have a init py file? If not it might not be able to find the home.py file.
Can you post the contents of home.py? There might be something in there that is causing it not load correctly.

Have you put 'community_web' into your installed apps section of your settings.py?
http://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'community_web',
)

Related

Wagtail {{document.url}} is returning a 404 for user-uploaded files, in production

I've inherited a Wagtail CMS project but have been unable to solve an issue relating to document uploads.
Having uploaded a file through the CMS, it arrives in the documents directory /var/www/example.com/wagtail/media/documents/test_pdf.pdf which maps to the /usr/src/app/media/documents/test_pdf.pdf directory inside the docker container.
In the front end (and within the Wagtail dashboard) the document.url resolves to https://example.com/documents/9/test_pdf.pdf/ which returns a 404. Obviously the model number segment is missing from the file path above, but I read on a forum that
In Wagtail, documents are always served through a Django view (wagtail.wagtaildocs.views.serve.serve) so that we can perform additional processing on document downloads
so perhaps this, in itself, is not an issue.
There are a couple of lines in urls.py file which look correct:
urlpatterns = [
url(r'^django-admin/', admin.site.urls),
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^search/$', search_views.search, name='search'),
url(r'^sitemap\.xml$', sitemap),
url(r'', include(wagtail_urls)),
# url(r'^pages/', include(wagtail_urls)),
]
if settings.DEBUG:
...
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and in base.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/
So, my hunch is one of either:
Uploads being stored incorrectly, in a single folder rather than in subdirectories by model
The routing to this “virtual” directory is broken, so it’s breaking at the "check permissions" stage (but I couldn't figure out how routing works in Django) and returning the 404
The web server is incorrectly configured, so whilst the “virtual” URL is fine it’s actually the file URL which is broken and THIS causes the 404 (my nginx contains a /media/ location but not a /documents/ location, as I would have expected)
Something else entirely (my next step is to pull a copy down to my own machine and see if the issue still occurs)
I appreciate there isn't much to go on here but I'm hoping that someone might be able to give me some pointers as to what else I should check, as I've been banging my head against this for most of the day.
My background is with Ruby on Rails so, as with that framework, I've a feeling that there is a lot of "magic" happening behind-the-scenes that is making it very tricky to figure out what's going on.
Thanks!
You are able to see documents while developing because of
if settings.DEBUG:
...
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Like static files media files should be handled on server level. For example, if you are using GCP you need to update your app.yaml and add media/ the same way as static/
...
handlers:
- url: /static
static_dir: static/
- url: /media
static_dir: media/
...

Static method returning empty list in Django

I am trying to run a Django app on local server. It works fine on mu Ubuntu machine but in mac, I can't get the CSS for
localhost:8000/admin
and
localhost:8000/docs to load.
On digging further, I found out that the static URL in main "urls.py" file
return an empty list instead of a URL pattern.
Does anyone have an idea why it is like that on the new mac system?
I have had the same issue. I was able to fix it manually by adding the following snippet to my urls.py file in the project (the urls.py file next to settings.py)...
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
. . .
if settings.TESTING_PRODUCTION:
urlpatterns += [
re_path(r'^static/(?P<path>.*)$', serve, {
'document_root': settings.STATIC_ROOT,
}),
]
I pulled this together from the Django Docs here.
I needed to do this so that I could test the "production" environment with manage.py runserver by manually setting DEBUG = False in settings.py which changes a few other URLs and also turns off trace printing in my code.
In my settings.py file, I have some code to set TESTING_PRODUCTION to True as well. But in actual production with a real web server, the code should set TESTING_PRODUCTION to False so that the static files can be served by the webserver directly and not through Django.

Django runserver not serving some static files

My local testing server for Django v1.8.2 on Windows 8.1 is only serving certain static files. Others are giving a 404 error.
#urls.py - excerpt
urlpatterns = [
url(r'^$', views.index)
] + staticfiles_urlpatterns()
#settings.py - excerpt
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
'users'
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
As far as I can tell the development server is configured to serve static files. When running runserver I get no warnings, and my code displays no syntax errors (import statements do exist and so forth). I did for testing purposes run collectstatic before starting the server just to be sure at least once.
My view template is:
{% load staticfiles %}
<img src="{% static 'main/img/ComingSoon.jpg' %}" alt="Coming Soon">
The link generated is /static/main/img/ComingSoon.jpg which looks correct, the file does exist in that location. What perplexes me is that this directory produces a 404 error, but other static files are served. The directory hierarchy is:
static/
admin/
css/
..
js/
..
img/
..
main/
img/
ComingSoon.jpg
The URL localhost:8000/static/admin/img/ gives an expected message about indexes being not allowed. However, localhost:8000/static/main/img/ reports \main\img\ cannot be found. Both are 404 statuses. Images within static/admin/img/ do display correctly with the same links as what is giving an error. The Administration site for Django does display correctly.
Why would one directory within static/ not be indexed or accessible?
According to the Django documentation regarding static/:
This should be an initially empty destination directory for collecting
your static files from their permanent locations into one directory
for ease of deployment; it is not a place to store your static files
permanently. You should do that in directories that will be found by
staticfiles’s finders, which by default, are 'static/' app
sub-directories and any directories you include in STATICFILES_DIRS).
I moved the files to another directory such as:
myApp/
main/
static/
main/
img/
..
static/
..
After running collectstatic I noticed the script created the subdirectories in myApp/static/ as expected and it must have generated the URLs needed because it now properly serves the files.

Cannot get django-debug-toolbar to appear

No matter what I do, I simply cannot get django-debug-toolbar to appear. I've tried everything suggested in every answer on this question.
I have DEBUG=True in my settings
I have django.contrib.staticfiles and debug_toolbar in INSTALLED_APPS
I have 'debug_toolbar.middleware.DebugToolbarMiddleware' high up in MIDDLEWARE_CLASSES
I have INTERNAL_IPS = () in my settings
I tried adding print("IP Address for debug-toolbar: " + request.META['REMOTE_ADDR']) in a view, and it printed IP Address for debug-toolbar: 127.0.0.1
I have a closing </body></html> in my template
I have run pip install django-debug-toolbar in my virtualenv, without any issues
I have run python manage.py collectstatic and there is a debug_toolbar directory in my static files
When I run the app, I see no request in the console for any URLs containing django_debug_toolbar, so I suspect it's the application not being loaded.
I don't see any failed requests in the developer console, either.
I've read the django-debug-toolbar installation docs and am out of ideas.
Does anyone have any suggestions for debugging? I'm running OSX and Django 1.7. The curious thing is that debug-toolbar WAS appearing just fine - I think I've made some tweak that caused it to vanish, but I don't know what.
UPDATE: I've even tried adding this in my settings file, which is supposed to force the toolbar to appear:
def show_toolbar(request):
return True
SHOW_TOOLBAR_CALLBACK = show_toolbar
But it doesn't help.
I've also tried throwing a deliberate exception in my view, so that I can check DEBUG is on and all the settings are as above. They are, and still no toolbar!
UPDATE 2: When I set INTERNAL_IPS=('127.0.0.1',), I start to see debug-toolbar requests in the console, but no toolbar on the page.
And the following HTML appears in my page - so the toolbar is there, but it's not visible because it's got display=none set all over it:
I had the same problem but managed to fix it following dvl's comment on this page. Here is a summary of the fix:
In settings.py
if DEBUG:
MIDDLEWARE += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
INSTALLED_APPS += (
'debug_toolbar',
)
INTERNAL_IPS = ('127.0.0.1', )
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
In the project urls.py, add this url pattern to the end:
from django.conf import settings
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
Some information for news users as me, when dev on virtual or remote machine
Add this ligne in a views.py file
print("IP Address for debug-toolbar: " + request.META['REMOTE_ADDR'])
When the views is call, you can see the client IP in the shell
You have to add this IP the settings.py file
INTERNAL_IPS = ('IP')
All of the divs with display: none; are in fact behaving properly. They won't change to display: block; until you actually click on them in the toolbar itself.
The button used to toggle the toolbar is the div with an id="djDebugToolbarHandle". As you can see in your console, this button has a top position of 2310px. What this means is that it is rendering, but it is just way down off the page.
Try typing the following in the console to reset its position:
document.getElementById('djDebugToolbarHandle').style.top="30px";
I had the same problem. Changing the finder module in my settings.py worked for me:
STATICFILES_FINDERS = (
#'django.contrib.staticfiles.finders.FileSystemFinder', #THIS BREAKES debug_toolbar
'django.contrib.staticfiles.finders.AppDirectoriesFinder', #THIS WORKS
)
Make sure to clean the browser cache after this change.
But after this, Django gave me error messages during collectstatic, due to this issue. I solved creating two configurations in my settings.py:
class Production(Base):
DEBUG = False
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
)
class Develop(Base):
DEBUG = True
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
I hope it helps.
One reason why django-debug-toolbar might appear but not appear correctly, (items stuck in "Loading") is if manage.py collectstatic has not been run. Just thought I'd post that here in case it helps someone.
i was have same issue with django-toolbar
all tags have class djdt-hidden and hidden
<div id="djDebug" class="djdt-hidden" dir="ltr" data-default-show="true">
i using pycharm and GoogleChrome
just using FireFox and it was fixed

Directory 'uploads/' for the site filebrowser.filebrowser does not exist

I've managed to use django-filebrowser to upload file via TinyMCE based on this documentation:
http://django-filebrowser.readthedocs.org/en/latest/quickstart.html
I've put reference to tiny_mce.js and tinymce_setup.js from Grappeli folder to my template,now TinyMCE works.
but when testing filebrowser with this command:python manage.py test filebrowser I get this error:Directory 'uploads/' for the site filebrowser.filebrowser does not exist. ,of course all of project throw this error.I searched this error in google but no proper result!
Note:I've gotten Grappeli worked already.
what do U think?
For those having problems with filebrowser setup, here is what is required to set it up after you install it.
Add it to your INSTALLED_APPS as:
'filebrowser',
In your urls.py master file, add the file browser pattern:
from filebrowser.sites import site
urlpatterns = patterns('',
(r'^admin/filebrowser/', include(site.urls)),
....)
Then make sure you have your MEDIA_ROOT set and that by default the uploads/ folder exists in the MEDIA_ROOT. You can change the uploads folder by settting FILEBROWSER_DIRECTORY to something different:
FILEBROWSER_DIRECTORY = 'filebrowser_uploads/'
Then I usually run a test and see if anything is broken and why:
python manage.py test filebrowser
I don't know why the setup doesn't create the default directory for it if MEDIA_ROOT exists. Instead it checks if MEDIA_ROOT + FILEBROWSER_DIRECTORY exist and it fails if it doesn't. More on this in the quick start guide.