importing image to django page - python

I am trying to attach an image to my page (per https://docs.djangoproject.com/en/1.10/howto/static-files/#configuring-static-files), but it cannot be displayed: http://prntscr.com/evwern
settings.py
STATIC_URL = '/portfolio/'
urls.py
urlpatterns = [
url(r'^$', index, name='index'),]
index.html
{% load static %}
<img src="{% static '/catalog/static/portfolio/oh_i_ah.jpg' %}" alt="My image" style="width:640px;height:473px;"/>
Path to the image: mysite/portfolio/catalog/static/portfolio/oh_i_ah.jpg
If I try to open the image in the new tab it throws:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/portfolio/catalog/static/portfolio/oh_i_ah.jpg

1) You did not specify your app directory name. Need to know the app/directory name to answer your question properly.
2) You did not use 'static' properly.
3) You did not specify whether you are using default django development server or some production server. I am assuming that it's default django development server with DEBUG=True.
Solution
Let's imagine: You have an app named app0 (let's say you created that with "python manage.py startapp app0") and you have created a directory called "static " inside of that (following default django convention over configuration). Inside of this 'static' directory you have created another directory called 'app0'. So, you are going to put your file inside "/app0/static/app0". So, your file path becomes: "/app0/static/app0/oh_i_ah.jpg"
Now, set STATIC_ROOT properly in the settings.py
In the template file refer the file as {% static "app0/oh_i_ah.jpg" %} (without leading forward slash).
Now, everything will be ok.
Yes, you can put the static files outside of any app directory if you configure STATICFILES_DIRS, STATIC_ROOT in settings.py correctly.
Please properly describe your problem with as much details as possible so that we can help you in the right way.

in settings.py
import os
STATIC_URL = '/portfolio/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
and
python manage.py collectstatic
in index.html
{% load staticfiles %}
<img src="{% static '/portfolio/oh_i_ah.jpg' %}" alt="My image" style="width:640px;height:473px;"/>

Related

Unable to connect background Image with static file Django

I have following html template
<div class="owl-slide cover" style="background-image: url({% static 'img/slides/slide_home_2.jpg'%});">
</div>
But I am not able to load static background.
my static directory is same as it is in django project path along with templates.
here is my part of setting.py for static files
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/',)
Everything seems look ok but my background is not working any suggestion will be helpful
Sorry to hear that. I don't know if you have solved you issue meanhwile.
In my settings.py I have the following STATIC setting
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Within every Django-App in my Django-Website I have a directory like this
<app-name>/static/<app-name>/...
And within the templates I am using the following code:
At the very beginning
{% load static %}
What I also recognized in your code is that your path starts with "img/"
If I want to refer to an image then I use
{% static "<app-name>/image.png" %}
at least when deploy on a server I have to execute the following command so Django collects all static files and make it available.
python manage.py collectstatic
Maybe this helps?

How to add my own files to django 'static' folder

I've read django static files document and made my django static files settings like this
setting.py
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(PROJECT_PATH, 'static')
STATIC_URL = '/static/'
html page
<img src="{% static "admin/img/author.jpg" %}" alt="My image"/>
So if I address one of django default static files, it works fine. But if I add my own file and folders to the static folder, it doesn't show it.
I tried
python manage.py collectstatic
But nothing changed. How can I make it work?
A few things...
STATICFILES_DIRS = (
'path/to/files/in/development',
)
STATIC_ROOT = 'path/where/static/files/are/collected/in/production'
When DEBUG = True, Django will automatically serve files located in any directories within STATICFILES_DIRS when you use the {% static 'path/to/file' %} template tag.
When DEBUG = False, Django will not serve any files automatically, and you are expected to serve those files using Apache, Nginx, etc, from the location specified in STATIC_ROOT.
When you run $ manage.py collectstatic, Django will copy any and all files located in STATICFILES_DIRS and also files within any directory named 'static' in 3rd party apps, into the location specified by STATIC_ROOT.
I typically structure my project root as such:
my_project/
/static_assets/ (specified in STATICFILES_DIRS)
/js
/images
/static (specified in STATIC_ROOT)
I hope that helps you understand how the staticfiles app works.
STATIC_ROOT is where files are collected and moved to when collectstatic runs.
If you want files to be consolidated to there they should be found by the static file finder.
As an example, include the following in your settings
STATICFILES_FINDERS = ("django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder")
now for one of the apps that are a part of your project, create a folder called static and put something in it.
When you run collectstatic you should see that file mentioned and it copied to your STATIC_ROOT
You can try adding
STATICFILES_DIRS = (
STATIC_PATH,
)
to your settings.py.
Also, if you haven't already, make sure to include
{% load static from staticfiles %}
in each of your templates where you wish to reference static files.
Lastly, make sure that the file you are referencing actually exists and the file path to it is correct.
Try to:
<img src="{{ STATIC_URL }}admin/img/author.jpg" alt="My image"/>
And in your view must be something like this:
...
from django.shortcuts import render_to_response
from django.conf import settings
def my_view(request):
...
static_url = getattr(settings, 'STATIC_URL')
...
return render_to_response(
template_name,
RequestContext(request, {
'STATIC_URL': static_url,
}))

Django CSS. I get the HTML page with no CSS

I have had this problem for a while now, I have been trying to move my CSS file all over the place and changing the settings, and even messing with the media url stuff, which I don't believe I should be now that I have read other questions.
My CSS file is in the /home/justin/test/static/ directory. My templates are in the /test/templates directory.
My settings are:
STATIC_ROOT = '/home/justin/test/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
'/home/justin/test/static/',
)
My urls are:
urlpatterns = patterns('',
url(r'^$', 'views.home'),
# Static Files
url(r'^static/(?P<path>.*)$','django.views.static.serve', {'document_root':settings.MEDIA_ROOT}),
)
I have all three in my main template.
<link rel="stylesheet" href="/static/style.css" />
<link rel="stylesheet" href="{{ STATIC_URL }}style.css" />
<link rel="stylesheet" href="{{ STATIC_URL }}/style.css" />
They come out:
<link href="/static/style.css" rel="stylesheet"></link>
<link href="style.css" rel="stylesheet"></link>
<link href="/style.css" rel="stylesheet"></link>
The first comes out to the correct file, but it doesn't work.
Any help is really appreciated. Thank you.
My views.py:
from django.shortcuts import render_to_response
def home(request):
return render_to_response('index.html',{})
My error from the terminal is:
[16/Aug/2013 21:00:21] "GET /static/style.css HTTP/1.1" 500 1729
You need to pass request in RequestContext of your views
def home(request):
return render_to_response('index.html', locals(), context_instance = RequestContext(request))
Only then your session data will be passed to the template and {{ STATIC_URL }} will work.
Here are some tips to help you solve this problem.
First, anything to do with MEDIA_ is referring to files that are uploaded to the system by users; and STATIC_ refers to files that are part of your application.
STATIC_ROOT should point to the file system path where the collectstatic command will dump all the static files from all your applications. When you are deploying the application into a production environment, you run collectstatic (which will overwrite everything in the directory pointed to by STATIC_ROOT) and then copy the contents of this directory to a location that is mapped to the url that STATIC_URL points to.
In summary:
If your application needs any static files (images, javascript, css, etc.) create a directory called static in your application's directory (the same location where you have models.py) and add the files there.
STATIC_ROOT should point to a directory where all the images, css, javascript, etc. will be dumped by the collectstatic command. This is only used when you want to move your application to a production server. The collectstatic command will grab all the files in all the static directories in your applications that are listed in INSTALLED_APPS (including the ones from the django.contrib like the admin interface) and dump them in this directory. You would then take this directory and copy or move it to your web server.
STATICFILES_DIRS is a directory where any static files that are not part of any specific application should be stored. If this location is set, then django will also look here for static files.
STATIC_URL = the URL path that is configured in your web server to point to the location where all the files in STATIC_ROOT are located.
The {% static %} tag will always point to the STATIC_URL variable. In order to use this tag you must have {% load staticfiles %} at the top of any template that is using the tag; even if the template is inheriting from one that already as the load line in it.
You don't need anything fancy in your urls.py unless you are using django to serve your static files (which you should not do). Use the web server to handle static files. If you are running with DEBUG = True and using runserver, then django will take care of handling static files for you automatically as a courtesy during development.
For any user uploaded files which are controlled by the various MEDIA_* settings you need to handle these manually during development; and for this you can use the following snippet in your urs.py. Again, keep in mind this is only for development - do not use this in production:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Please read the static files section in the manual; from where I have summarized the above points.
Finally, you should use the render shortcut when using methods in your views. This makes sure that the proper request context is always sent.
you must use this tag ({% load static from staticfiles %}) in your template :
{% load static from staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" />
In your urls, you should serve from the STATIC_ROOT not the MEDIA_ROOT setting
url(r'^static/(?P<path>.*)$','django.views.static.serve', {'document_root':settings.STATIC_ROOT})
Also, you need to pass RequestContext on your views, like stated in other answers.
In development mode (which means DEBUG=True in settings.py), to serve static files
Simply put the following lines in urls.py
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
In production mode, you should use nginx/apache in front of django to serve static files.
Refs: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
There's a line in your question:
url(r'^static/(?P<path>.*)$','django.views.static.serve', {'document_root':settings.MEDIA_ROOT}),
Normally, settings.MEDIA_ROOT is for user uploaded files, which is a different folder from settings.STATIC_ROOT.

Django 1.3 Static Files

Like the 1 billionth static file question about Django 1.3. I've been searching and trying so many things but nothing seems to work for me. Any help would be appreciated. Will try and give as much information as possible.
URL FILE
urlpatterns = patterns('',
url(r'^projectm/statictest/$','project_management.views.statictest'),)
VIEW
def statictest(request):
return render_to_response('statictest.html',locals())
TEMPLATE
<html><head><title>Static Load Test Page</title></head>
<body>
{% load static %}
<img src="{{ STATIC_URL }}testimage.jpg" />
</body></html>
SETTINGS
STATIC_ROOT = '/home/baz/framework/mysite/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = ('',)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_DIRS = (
"/home/baz/framework/mysite/templates"
FILES
-bash-3.2$ pwd
/home/baz/framework/mysite/templates
statictest.html
-bash-3.2$ pwd
/home/baz/framework/mysite/project_management/static
-bash-3.2$ ls
testimage.jpg
Not too sure if there is any other information that would be helpful. But basically when I go to this test page and check the page source, the url is pointing to
<img src="/static/testimage.jpg" />
However the image does not load. I have tried this on multiple browsers too. Maybe I am missing an imort statement somewhere?
cheers for the help
Are you using the built in runserver command or do you serve the Django app some other way?
If you use runserver then your problem is that you don't tell Django where to find your static assets in the filesystem. You need to set STATIC_ROOT to a filesystem path where your static assets can be found. Try setting it to: /home/baz/framework/mysite/project_management/static/
If you are using a different server (like gunicorn behind Nginx for example) then it is the responsibility of the front-end server to intercept requests for /static/ and serve them for you.
Also remember to run the ‘collectstatic’ management command once you have set ‘STATIC_ROOT’.
https://docs.djangoproject.com/en/1.4/howto/static-files/#deploying-static-files-in-a-nutshell

How can I add css/image on webpage using django?

I put the image("hi.png") and css file in /home/user1/djangoblog/blog/static
In templates i have <img src="{{ STATIC_URL }}images/hi.png" />
I edited the settings.py =>
STATIC_ROOT = ''
STATIC_URL = "/static/"
STATICFILES_DIRS = (
"/home/user1/djangoblog/blog/static/",)
The web page source returns =>
<div><img src="/static/images/a.jpg" /></div>
If the views.py => The image is not displayed on the web page.
now = datetime.datetime.now()
#return render_to_response('current_datetime.html', {"foo": now}, context_instance=RequestContext(request))
t = loader.get_template('current_datetime.html')
c = Context({'foo': now})
return HttpResponse(t.render(c))
But if the views.py => it displays the images on the web page.
return render_to_response('current_datetime.html', {"foo": now}, context_instance=RequestContext(request))
It looks like it's a problem with HttpResponse or RequestContext. How can i fix this problem with HttpResponse or RequestContext?
You need to read the staticfiles docs more carefully.
You specify the absolute path to your static directory with STATIC_ROOT and the URL that directory can be accessed at through a browser via STATIC_URL. Your main static directory should never go in STATICFILES_DIRS. That setting is only to allow you to specify additional directories that should be processed while running the collectstatic management command.
In general, you never use your actual static directory. In development Django serves files from each app's static directory and any directories in STATICFILES_DIRS (excluding the main static directory). In production, you run the collectstatic management command and then setup your main webserver (Apache, Nginx, etc) to serve files from STATIC_ROOT. Django never serves anything from the main static directory (STATIC_ROOT).
I suspect the problem is that you don't have the staticfiles context processor in your settings file. That's the reason that /static/ isn't being inserted where you've put {{ STATIC_URL }}.
It's as simple as putting
'django.core.context_processors.static',
Into the list of context processors (TEMPLATE_CONTEXT_PROCESSORS) in your settings.py file.
Update
I added this in TEMPLATE_CONTEXT_PROCESSORS but still that didn't work. – guru 3 hours ago
Adding 'django.core.context_processors.static' to the list of context processors did fix your problem because as you can now see, it is inserting the value for STATIC_URL wherever it sees {{ STATIC_URL }} in your templates. The error is that you've changed the value of STATIC_URL to "/home/user1/djangoblog/blog/static/" probably because you've been confused by some of the answers here.
Change the value of STATIC_URL back to '/static/' so that line should read
STATIC_URL = '/static/'
That will fix your problem.
Django templates simply put whatever is in the variable into the template. They don't care what it is or what it represents. If the value of STATIC_URL is /home/user1/djangoblog/blog/static/ then it dutifully inserts /home/user1/djangoblog/blog/static/ wherever it sees {{ STATIC_URL }} which is why you are seeing
<img src="/home/user1/djangoblog/blog/static/images/a.jpg" />
whenever it renders the template containing <img src="{{ STATIC_URL }}images/a.png" />

Categories