Django geting error when loading static files? - python

I have the code below to load static files, but I keep getting a TemplateSyntaxError. Does anyone know how I can fix this issue?
Template:
{% load staticfiles %}
{% load static %}
<img class="logo" alt="Test Pic" src="{% static 'images/logo.png' %}" width="110" height="70">
{% block main %}
{% endblock %}
Settings:
INSTALLED_APPS = [
...,
'django.contrib.staticfiles',
]
STATIC_URL = '/public/'
STATIC_ROOT = os.path.join(BASE_DIR, "public")
URLS:
urlpatterns = [
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Error I get:
Invalid block tag on ...: 'static', expected 'endblock'. Did you forget to register or load this tag?

Just use {% load static %} on the top since it is recommended in newer versions of Django. I think using staticfiles and static at the same time creates a confusion.

What fixed the issue was reinstalling Django.

Related

my static files like images are not displayed after deploying my django 2.2 app

when I deploy my django 2.2 app on OVH but the static files like the image is not displayed even though the path is correct
myapp/settings
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static'),
]
STATIC_URL = '/static/'
index.html
{% extends 'layout/base.html' %}
{% load static %}
{% block content %}
<img src="{% static 'images/fondu2.png' %}" style="width:500px;height:500px">
{% endblock content %}
myapp/urls.py
.......
from .import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index, name='index'),
]
where is the problem?

user uploaded image is not displaying

Image uploaded by user is not displaying though i have not done wrong in template. Also i have defined MEDIA_URL and MEDIA_ROOT. What might be the reason for not getting image displayed?
Code
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
project/urls.py(urls.py of main project)
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('shop.urls', namespace='shop')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
templates/shop/product/list.html
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %} {{ product.image.url }} {% else %} {% static 'img/no_image.png' %} {% endif %}" >
</a>
I know this question is asked multiple times but my code took after the documentation and still i could not display image. Could anyone help me, please?
It is working now after fresh restart of the server. So the above code and process of serving media files is correct.

Display images on Django Template Site

I read a lot about including image files, but i still don't get it :(
my models.py
class Movie(models.Model):
image_url = models.URLField(max_length=1024, blank=True, null=True)
image_file = models.ImageField(upload_to='poster/', blank=True)
my index.html
{% load staticfiles %}
<img src="{% static "{{movie.image_file}}" %}" />
The pictures are saved on harddisk /myapp/poster
Thanks for helping.
Got it!
<img src="
{% if movie.image_file %}
{{ movie.image_file.url }}
{% else %}
another-image.jpg
{% endif %}"
/>
urls.py
+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
added MEDIA_URL
Thanks a lot!
You just need to do:
<img src="{{ movie.image_file.url }}" />
User uploaded files go to your MEDIA_ROOT + the upload_to parameter in your model field, which is typically a different location that static files are served from when using the {% static %} template tag.
Since your field allows for blank=True you can use a conditional to show a different image, or no image at all: (spaces added to avoid wrapping)
<img src="
{% if movie.image %}
{{ movie.image_file.url }}
{% else %}
another-image.jpg
{% endif %}"
/>
alternatively, you could add a model property that does the same thing, or you can just wrap the entire image tag in the if statement to hide it if the field is empty.
Set MEDIA_ROOT and add following lines at the end of your urls.py
+static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Example:
urlpatterns = patterns('',
url(r'^$', views.index, name='Index'),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In img src write {{MODEL_NAME.FIELD_NAME.url}}
This is only for development.
Refer https://docs.djangoproject.com/en/1.8/howto/static-files/

Django can't show images on page

I'm desperatly trying to load some images to and from my database with the help of Django.
Loading seems to work, but getting them back from the database and showing them on a webpage doesn't seem to work.
Here some info:
Environment:
myproject
|_forpix(my app)
|_myproject
|_media
|_images
|_mimicry3.png
I have a base.html wich includes a contentblock "allimages.html":
{% extends "base.html" %}
{% block content %}
<div id="imagelist">
{% for image in images %}
<p><img src="{{MEDIA_ROOT}}{{image.picture.url}}" />{{ image }}</p>
{% endfor %}
</div>
{% endblock %}
This gives me the following result:
And if I click on one of the images i get:
In my settings.py I've set the following:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates/'),)
Now i really don't know how to fix this.
Can anybody provide me with some help (not the django tutorial, I've been there, tried that)
Do I have to add something in the urls.py especially for the media file? Or is it something else?
If i need to provide extra info, just ask.
^media/$ is a very wrong regex for media files. You should delete the $ (end-of-the-string) sign from this regex.
Usually for development environments I use this snippet in the urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Also remove the useless {{ MEDIA_ROOT }} part from your template code. It should be:
<img src="{{ image.picture.url }}" />
In adition the line that you have to add is..
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
But it has to be in the urls.py of your project folder. not in the urls.py of your App folder. I knew it by mistake.

django - static files in base template

How to make base template use static files and to make other templates that inherits base template to use same static files?
As I read in django documentation it writes about how to use static files that are used for specific app. But I can't seem to find a way to make it use static files from outside app.
Given app inherits everything, but static files.
My settings.py:
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'myproject.apps.finance',
'myproject.apps.base',
'django.contrib.admin',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
)
This is my current homepage settings:
url for homepage:
from django.conf.urls import patterns, include, url
from myproject.views import hello
urlpatterns = patterns('',
('', hello),
)
view of homepage:
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponse
import datetime
def hello(request):
hello = "Hello World"
return render_to_response('home/home.html', {'hello': hello})
homepage template:
{% extends "base/base.html" %}
{% block title %} My Homepage {% endblock %}
{% block content %}
<p>I say {{ hello }}</p>
{% endblock %}
base template:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<link rel="stylesheet" href="{{ STATIC_URL }}/css/style.css">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My Personal Finance Site</h1>
{% block content %}{% endblock %}
{% block footer %}
<section class="divider1">
<p>Thanks for visiting my site.</p>
<p>All rights reserved</p>
</section>
{% endblock %}
</body>
</html>
my CSS file is located in empty project called base. But I think there could be better way to use static files that are outside given app.
So what would be the best way to link base template with css file to make other templates that intherits base, to get same css file configuration?
base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
{% block css %}
<link rel="stylesheet" href="{{ STATIC_URL }}/css/style.css">
{% endblock %}
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My Personal Finance Site</h1>
{% block content %}{% endblock %}
{% block footer %}
<section class="divider1">
<p>Thanks for visiting my site.</p>
<p>All rights reserved</p>
</section>
{% endblock %}
</body>
</html>
page.html
{% extends "base/base.html" %}
{% block title %} My Homepage {% endblock %}
{% block css %}{{block.super}}
//put css here
{% endblock %}
{% block content %}
<p>I say {{ hello }}</p>
{% endblock %}
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from project_name import settings
admin.autodiscover()
urlpatterns = patterns('',
.......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
settings.py
import os
import sys
..........................
SITE_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(SITE_ROOT, 'app_name'))
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(SITE_ROOT, 'staticfiles'),
)
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.
os.path.join(SITE_ROOT, 'templates'),
)
....................
make sure that the template tag "{% load static %}" is at the top of your .html file. that will load your static folder.
sample
{% load static %}
{% extends "base/base.html" %}
{% block title %} My Homepage {% endblock %}
{% block css %}{{block.super}}
//put css here
{% endblock %}
{% block content %}
<p>I say {{ hello }}</p>
{% endblock %}

Categories