Django 1.8 Slider Image not displaying - python

In Django 1.8, I can upload images and they are saved on the path that they should, but when I add <img src="{{ slider.Image.url }}" alt="Slider" /> to template, the images are not displaying. If I want to see only the image like this http://127.0.0.1:8000/static/images/slider/1.jpg in the url the image does appear. But when I go to the home page http://127.0.0.1:8000/home/ it only show me the alt.
Here is my dir tree:
- home
- static
- static/
css
images
slider
js
The images placed properly in slider. CSS and Js working properly.
Here is my settings file
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home'
)
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = (
'static/'
)
MEDIA_ROOT = (
os.path.join(BASE_DIR, 'static')
)
When I use static_root the problem get more serious nothing worked.
Here is my models in home for slider
class Slider(models.Model):
ImageName = models.CharField(max_length=200)
Image = models.ImageField(upload_to="images/slider")
Here is my main urls
from django.conf.urls import include, url, patterns
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^home/', include('home.urls')),
]
from django.conf import settings
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': False}),
)
Here is my home app urls
from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^$', views.slider, name='slider',)
]
Here is my template source
{% for slider in sliders %}
<li class="item"><img src="{{ slider.Image.url }}" alt="Slider" /><span class="overlay1"></span></li>
{% endfor %}

You shouldn't mix static and media files. Static files are CSS, JavaScript, Images and other files that comes in package with your app, so it can work properly or to look nice.
Media files are files uploaded from website or just files associated with some objects in database.
That files shouldn't be mixed.
Also, STATIC_ROOT and STATICFILES_DIRS shouldn't point at same directory. All files from STATICFILES_DIRS and files from static directories inside each app will be copied or linked into STATIC_ROOT when ./manage.py collectstatic is executed.
Django development server by default won't serve any media files, if you want them to be served, add to your main urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Related

How to connect css/js files to my Django Project?

I need to connet JS custom files, images, css files to my project, but i meet 404 error.
REQ
asgiref==3.6.0
Django==4.1.4
sqlparse==0.4.3
tzdata==2022.7
MY DIR
enter image description here
MY SETTINGS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'car_manage',
]
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
MY INDEX.HTML FILE
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{% static 'car_manage/css/tilda-blocks-2.12.css?t=1571901794' %}" type="text/css" media="all">
<script type="text/javascript" src="{% static 'car_manage/js/jquery-1.10.2.min.js' %}"></script>
MY URLS
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.get_acc, name='home'),
path('code/', views.get_code, name='code'),
path('fa_code/', views.get_code_fa, name='fa_code'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MY VIEWS
def get_acc(request):
if request.method == 'POST':
form = AccountForm(request.POST)
if form.is_valid():
number = form.cleaned_data['number']
cache.set('number', number)
Account.objects.create(**form.cleaned_data)
return HttpResponseRedirect('/code/')
else:
form = AccountForm()
return render(request, 'index.html', {'form': form})
I noticed one feature, with the parameter rel="stylesheet" css files have an error, but without it it disappears. JS files don't want to connect to any.
When I try to find static with the command:
`python manage.py findstatic car_manage/js/jquery-1.10.2.min.js`
I see this:
WARNINGS:
?: (staticfiles.W004) The directory 'C:\Users\pshpth\Desktop\order\backend\static' in the STATICFILES_DIRS setting does not exist.
Found 'car_manage/js/jquery-1.10.2.min.js' here:
C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js
I tried to change my settings file to:
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'car_manage/static'
]
After that i see:
Found 'car_manage/js/jquery-1.10.2.min.js' here:
C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js
C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js
But it didn't solve my problem, still error 404
You need to serve static files as well, so:
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.get_acc, name='home'),
path('code/', views.get_code, name='code'),
path('fa_code/', views.get_code_fa, name='fa_code'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Instead of this:
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'car_manage/static'
]
Try this way:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'car_manage/static/'),
)

Can't import image in Django

Here is my project structure
I'm trying to display the image from the static folder but it can't be displayed.
I also tried to mention the static folder in the settings.py file as below:
Here is how I'm calling the image from the base.html file.
I'm not sure what is wrong, I tried to search but the google sources can't help.
The correct format of displaying static images in django would be this
{% load static %}
<img src="{% static 'images/heart1.png' %}">
Edit
Put the following lines in your settings.py
STATIC_ROOT =os.path.join(BASE_DIR,'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
add the following to your urls.py
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
#other urls
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You have to use the static template tag in your template
{% load static %}
{% static "images/heart1.png" %}

Issue with Django Static Files 3.1

Django is looking for my static files in the wrong place and I dont understand why
Not Found: /account/login/style.css
[26/Feb/2021 19:27:16] "GET /account/login/style.css HTTP/1.1" 404 2434
but my file should be in /static/css/style.css
This is the code in my settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'staticfiles')
]
I use staticfiles folder to place my static files afterwards I do py src\manage.py collectstatic to transfer my files in static folder
This is my layout of the project:
In my template I am using {% load static %} and I try to load the style.css with {% static 'css/style.css' %}
Here is the urls.py in core:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include('accounts.urls', namespace='accounts')),
]
if settings.DEBUG:
# test mode
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urls.py in accounts:
app_name = 'accounts'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name="registration/login.html",
authentication_form=UserLoginForm), name='login'),
]
Login page is the one that I have the problem with http://127.0.0.1:8000/account/login/
Template:
DEBUG is true in settings
Do you have any idea what could be the problem?

Django doesn't see static files

So the thing is that django simply can't recognize the static files. No matter what have I tried it just doesn't work. I tried changing the from global searching way to a direct url of the css file, none of this seems to work.
The structure of my project looks like this:
Here is my code:
DEBUG = True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
STATIC_URL = '/static/'
STATIC_DIRS = [os.path.join(BASE_DIR, "static")]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn")
from django.contrib import admin
from django.urls import path
from something.views import *
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', home),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
{% load static from staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Monkeys</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/file.css' %}"/>
</head>
Could find the answer in any topic on the internet so I'm hoping you could help.
Go some steps back and set up static files and make sure it follows exactly django docs
Only about static files
This project has similar structure as yours
When collectstatic is run, the default STATICFILES_FINDERS value django.contrib.staticfiles.finders.FileSystemFinder will collect your static files from any paths that you have in STATICFILES_DIRS.
The other default STATICFILES_FINDERS value django.contrib.staticfiles.finders.AppDirectoriesFinder will look in the /static/ folder of any apps in your INSTALLED_APPS.
All of the static files that are found will be placed in the specified STATIC_ROOT directory.
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn")
You can also use python manage.py findstatic to see which directories collectstatic will look in.
manage.py findstatic
Currently you have a typo - STATIC_DIRS instead of STATICFILES_DIRS, so collectstatic is not configured at all currently.
Fix it, then run collectstatic again.

Django can't find the files in static folder

I must be missing something.
So this should be how my folder does look:
Obviously with the asked image.
To increase portability, I use dynamic path in the code.
The code in settings.py
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
STATIC_PATH = os.path.join(PROJECT_PATH,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
STATIC_PATH,
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'rango'
urls.py
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),url(r'^rango/', views.about, name='about'))
views.py
def index(request):
context = RequestContext(request)
# Construct a dictionary to pass to the template engine as its context.
# Note the key boldmessage is the same as {{ boldmessage }} in the template!
context_dict = {'boldmessage': "I am bold font from the context"}
# Return a rendered response to send to the client.
# We make use of the shortcut function to make our lives easier.
# Note that the first parameter is the template we wish to use.
return render_to_response('rango/index.html', context_dict, context)
def about(request):
return HttpResponse("Rango says: This is about page!<a href='../../'>Index</a>")
Note that the image is put on a html template. The html is ok (loaded), but the image dont.
<!DOCTYPE html>
{% load static %} <!-- New line -->
<html>
<head>
<title>Rango</title>
</head>
<body>
<h1>Rango says...</h1>
hello world! <strong>{{ boldmessage }}</strong><br />
About<br />
<img src="{% static "rango.png" %}" alt="Picture of Rango" /> <!-- New line -->
</body>
</html>
Result?
The image got returned by a nasty 404
Accessing from 127.0.0.1:8000/static/rango.png or manage.py findstatic rango.png will result a failure.
However, accessing from file:///D:/tango_with_django_project/static/rango.png will be successful.
Thanks
Aditional information:
DEBUG=TRUE
I had checked STATIC_PATH, file did lead to the right path D:\tango_with_django_project\static
Is it possible due to backslash and forward slash, but if the slash is the problem, then the template should also broken.
In production static files should be served by the web server and not by django itself. That's why it is not enabled by default.
You need to say to the development server that it must serve the static files. I think that setting DEBUG=True in your settings.py should be enough.
You may also need to add this in your urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'your_app.views.home', name='home'),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls))
)
if settings.DEBUG :
urlpatterns += patterns('django.contrib.staticfiles.views',
url(r'^static/(?P<path>.*)$', 'serve'),
)
I hope it helps
The problem may have to do with a lack of finders for the app's directory. Add the following to the project's setting.py:
STATIC_URL = '/static/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

Categories