django not displaying image - django

I started with a django app and tried displaying an image in the home page. But the image is not getting displayed.
My settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR,"media")
MEDIA_URL = "/media/"
My urls.py:
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'myapp.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'',include('users.urls')),
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My home.html:
<html>
<head>
<title>MY SITE</title>
</head>
<body>
<img src="/media/image/myimage.jpg" alt="my image"/>
Welcome to my site
</body>
</html>
I get the text my image displayed instead of the image

ok, so I set up a simple 'paired-down' working example of this so no moving pieces were missing. Some Notes:
I used django 1.6
If you want to use a 'scale-able' delivery of static images you will want to follow
the django-1.6 staticfiles documentation which is what this example provides.
This means that you need to hack-n-slash your MEDIA references. ( MEDIA is really meant for file upload's) and you dont need to fool with the staticfiles_urlpatterns in your urls.py file. As you get this behavior out-of-the box when you add 'django.contrib.staticfiles' to your settings.py
Overview: Here is what your file tree-layout will look like in django 1.6, and the file structure that I am referencing in this answer.
├── djproj
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
├── manage.py
└─── myapp
   ├── admin.py
   ├── __init__.py
   ├── models.py
   ├── static
   │   └── myapp
   │   └── myimage.jpg
   ├── templates
   │   └── index.html
   ├── tests.py
   └── views.py
Step 1: Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
Step 2: In your settings file, define STATIC_URL, for example:
STATIC_URL = '/static/'
Step 3: change your home.html to look like this ( I used index.html in my example )
[ PROJECT_HOME/myapp/templates/index.html ]
<html>
<head>
<title>MY SITE</title>
</head>
<body>
{% load staticfiles %}
<img src="{% static "myapp/myimage.jpg" %}" alt="My image"/>
Welcome to my site
</body>
</html>
Make sure to read the django-1.6 staticfiles documentation related to STATICFILES_STORAGE so you understand what these template tags are buying you. Hint: python manage.py collectstatic
Step 4: ( you may have already done this, but I did not see it) Make sure that TEMPLETE_DIRS is defined in your settings.py and includes your home.html ( key here is that django's template engine needs to be serving this as we will be using some template tags)
[ PROJECT_HOME/djproj/settings.py ]
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
BASE_DIR + '../myapp/templates',
)
Step 5: build a view that renders your home.html page.
[ PROJECT_HOME/myapp/views.py ]
from django.shortcuts import render_to_response
def index( request ):
return render_to_response('index.html')
Since this is a bit convoluted, and there are several moving pieces here: here is a changeset that shows the complete 'changes'
You can of-coarse pull the entire github project if any of this is confusing.
django-staticfiles-setupexample
Final Note: STATIC files were not always handled this way in django. The MEDIA dir used to be the settings attr you were after. So this answer is for Django 1.6 ( staticfiles were added in django version 1.3)( the directory layout was changed in django 1.5).
You can ( as you were trying to do) hardwire your media dirs to the STATIC defines. Altho I do-not recommend this. Which is why I did not describe how to do it this way.

You are adding the media urls too late in the list. Django will try to match each urlpattern in succession, stopping when it gets to the first one. In this case, it matches on r'' and doesn't get to the static files or the media urls.
You may be able to put each pattern in the single call to patterns(), instead of using +=. That would be the cleanest, but I can't test it here. A sure-fire way to do it would be to pull the "users.urls" line out and add it later, like so:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += url(r'',include('users.urls'))

I'd recommend you set DEBUG = TEMPLATE_DEBUG = True and request the image URL directly.
You'll get Django debug output either showing that the URL can't be matched or the file path it's actually looking for.
The settings look generally correct although you've not shared BASE_DIR which is important in this case.

I had been struggling with the issue for like an entire day yesterday... I finally gave up and moved on creating my site without worrying about the images. Then today I decided to check the responsiveness of the site. I found out that my URLs were okay since I had strictly been following the documentation and best practices. The chrome console was saying:
Failed to load resource: net::ERR_BLOCKED_BY_CLIENT
The issue was with HTTP Referral Policy. Check them out. So after doing some research, this helped a lot, I found out that AdBlock was blocking my referred images. Apparently, my /media/ path was flagged in one of their regex patterns, deciding that my images were redirections to Ads. The ironic thing is that my website is about ads... so it must have heavily factored in, as my site has words like 'ad' in its url patterns. Long story short, I disabled AdBlock and my images now render. So I think it might be worth considering that even with best practices in your Django code, such an error could be caused by something with your browser!

Related

How to create hierarchical urls within django app?

I have multiple app based django project and within some apps url scheme getting complicated due to number of models. Hence I'm looking a way to make a hierarchical url structure within the app.
In my project's urls file I do the following.
from order import urls as order_urls
In the order app I have urls.py and urls directory which contains separate url patterns for each model as follows.
In the app's urls.py file I import the model's urls as follows.
from urls import rental as rental_urls
urlpatterns = [
url(r'^rental-request/', include(rental_urls)),
]
This gives me the error: ModuleNotFoundError: No module named 'urls'
If I put __init__.py it gives me circular import error.
I'm not sure this is the correct way/possible for my requirement. Anyone could explain the correct way to achieve it?
Having a folder called urls (with an __init__.py file) as well as a file urls.py in the same folder will probably cause trouble to load the module order.urls from anywhere in your project. How does Python will know which file must be loaded ?
Consider this structure:
├── main.py
├── urls
│   └── __init__.py
└── urls.py
And this content for each file:
# urls/__init__.py
urlpatterns = "I'm in folder"
# urls.py
urlpatterns = "I'm in file"
# main.py
import urls
print(urls.urlpatterns)
When you run main.py, the result is:
% python main.py
I'm in folder
Possible solutions :
You may delete the urls.py and move its content to urls/__init__.py, or rename the folder urls to avoid conflicts and updates imports accordingly (in urls.py)

Static does not loads static files in Django

This is my directory structure
app_web
_init_.py
settings.py
urls.py
wsgi.py
upload_app
migrations/
static/
js/
alert.js
templates/
upload.html
_init_.py
admin.py
apps.py
models.py
tests.py
views.py
db.sqlite3
manage.py
In settings.py , my
STATIC_URL = '/static/'
and in my upload.html
{% load staticfiles %}
<script type="text/javascript" src="{% static "js/alert.js" %}"></script>
It does not works and throws 404 error everytime. I even tried load static but it still cannot load anything from static folder and throws 404 error.
I am using Windows 10 machine and Django==1.9
The idea was to create a static directory outside the upload_app folder. The reason is that in the settings.py the BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) . That means one directory above is the base directory, so it will start searching static/ from that directory. But it will never find it as I placed inside upload_app/static .
Also, I need to work on putting templates outside the app upload_app as it's not generally best practice to keep templates inside the app.
looking for other suggestions in structure

Django tutorial 1 not showing polls

I am taking a test Driven Development course for python (which is awesome) Obeythetestinggoat and so my Django needs work. So I'm taking the Djangoproject.com course and I get all the code entered and the server runs but the polls won't change.
The home page http://127.0.0.1:8000 shows
"It worked!
Congratulations on your first Django-powered page."
Which is great but it won't show the polls or the admin buttons and I've run out of ideas on how to redirect it but not sure the problem.
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
I'm rather proud that I figured out the server and other areas but I just don't know what I am missing to get the page to show the polls.
https://docs.djangoproject.com/en/1.10/intro/tutorial01/
Yes, all you need to do is go to http://127.0.0.1:8000/polls/ . Otherwise if you want put your default polls page on the home page like you intended to do in http://127.0.0.1:8000/
you could do this in your urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
hope it helps.
http://127.0.0.1:8000 is the main page of your preoject, but in the urls, you define (with regex) how to manage requests to http://127.0.0.1:8000/polls/ and http://127.0.0.1:8000/admin/. You should visit those URLs.
There's a urls.py at the wrong place made by the django-admin startproject mysite command.
.
├── db.sqlite3
├── manage.py
├── mysite
│   ├── asgi.py
│   .
│   .
│   │
│   ├── urls.py <-- right place
│   └── wsgi.py
├── polls
│   .
│   .
│   ├── urls.py
│   └── views.py
└── urls.py <-- wrong place
If you forget to remove it, and keep it, while creating the right one at the right place, it prevents the rules of the right one to be applied.

Overriding/Adding to Django URLs in settings rather than urls

It seems that the latest Django debug toolbar module has changed to middleware now and requires explicit URL setup to work. With my Django projects I always try to keep settings organised based on environment and not have if settings.DEBUG littered all over the settings files and project.
My settings layout is a general:
common.py (everything in here)
development.py (dev only things here)
production.py (prod only things here)
Is there a way in Django 1.10 I can add to the URLs in the development.py file so that I can keep away from if settings.DEBUG. Or will we be forced to use this method if wanting to use the new version of the debug toolbar?
I just find the below a bit of an anti-pattern
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
If you do not feel like testing for the value of settings.DEBUG in your URL configuration, you may manage your URLs with a pattern similar to the one you are using for your settings.
Instead of a urls.py file, you would have a urls package with this structure:
urls
├── __init__.py
├── common.py
├── local.py
└── production.py
In your different settings files you would specify which URL conf file to use this way:
# settings/local.py
ROOT_URLCONF = 'urls.local'
 
# settings/production.py
ROOT_URLCONF = 'urls.production'
The urls/common.py file will expose a urlpattern member containing all the URL patterns common to all configurations which you will import and use in urls/local.py and urls/production.py.
For example:
# urls/common.py
urlpatterns = [
# Put all common URL patterns here
]
 
# urls/local.py
from .common.py import urlpatterns as common_urlpatterns
urlpatterns = common_urlpatterns + [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
If you want my opinion, this solution feels like overkill given that, as opposed to settings, URL configurations should not differ much between environments.

Django include within single urls.py

I want to make an include in my urls.py referring to another urls in the same urls.py file.
My structure is as follows:
├── docs
├── requirements
├── scripts
└── sonata
├── person
│   ├── migrations
│   ├── templatetags
│   └── urls.py
├── registration
│   ├── migrations
│   └── urls.py
└── sonata
├── settings
└── urls.py
And I want every coming url with prefix 'pdf/' to add a value to kwargs and calling again the rest of url. This is my attempt:
urlpatterns = patterns('',
url(r'^$',TemplateView.as_view(template_name='registration/login.html')),
# This is my attempt for capturing the pdf prefix
# and calling this same file afterwards with the pdfOutput variable set to True
url(r'^pdf/', include('sonata.urls'), kwargs={'pdfOutput':True}),
url(r'^admin/', include(admin.site.urls)),
url(r'^person/', include('person.urls')),
url(r'^registration/', include('registration.urls')),
url(r'^menu/', registration_views.menu, name='menu'),
url(r'^customers/', person_views.customers, name='customers'),
url(r'^employees/', person_views.employees, name='employees'),
url(r'^alumns/', person_views.alumns, name='alumns'),
url(r'^teaching/', person_views.docencia, name='teaching'),
url(r'^i18n/', include('django.conf.urls.i18n')),
)
Is there any way of doing this? I looked at the docs. It seems pretty clear how to pass values, but after proving I can't make the include. (I don't want either to do include() with the [array] of patterns repeating all urls. This would break DRY principle).
Thanks in advance
The problem is that include immediately imports the included url configuration, resulting in a circular import error. You can do something like this, though:
sonata_patterns = [
url(r'^$',TemplateView.as_view(template_name='registration/login.html')),
url(r'^admin/', include(admin.site.urls)),
url(r'^person/', include('person.urls')),
url(r'^registration/', include('registration.urls')),
url(r'^menu/', registration_views.menu, name='menu'),
url(r'^customers/', person_views.customers, name='customers'),
url(r'^employees/', person_views.employees, name='employees'),
url(r'^alumns/', person_views.alumns, name='alumns'),
url(r'^teaching/', person_views.docencia, name='teaching'),
url(r'^i18n/', include('django.conf.urls.i18n')),
]
urlpatterns = [
url(r'^pdf/', include(sonata_patterns), kwargs={'pdfOutput':True})
] + sonata_patterns
Another possibility is to use middleware to capture the pdf prefix and set an attribute on the request. That way, you won't have to worry if all views accept your pdfOutput argument.