I've added in settings.py following:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
in urls.py:
urlpatterns = patterns('^/static/$',
# ... the rest of your URLconf goes here ...
url(r'^$', home, name='home'),
url(r'^admin/', include(admin.site.urls))
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
in models.py:
class Search(models.Model):
question = models.URLField()
query = models.CharField(max_length=255)
in views.py:
def home(request):
print ' base dir %s' % BASE_DIR
print ' static dir %s' % STATIC_URL
form = SearchForm()
return render_to_response('base.html', {'form': form},
context_instance=RequestContext(request))
and templates/base.html:
{% load staticfiles %}
<head>
<link href="{{ STATIC_URL }}bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="{{ STATIC_URL }}bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<title>Walker</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="form-group">
<form name="query">
{{ form.as_p }}
</form>
</div>
</div>
</div>
</div>
</body>
I ran ./manage.py collectstatic with no porblems, folder static being created.
When I execute ./manage.py runserver I can see in terminal this error:
base dir home/my/code/walker
static dir /static/
"GET /static/bootstrap/js/bootstrap.min.js HTTP/1.1" 404 1691
Template loading correctly. But bootstrap do not
Several hour can noot figure out what I need to do
If you store static files in locations other than app/static I think you need to specify STATICFILES_DIRS in your settings.py otherwise they will not be collected:
STATICFILES_DIRS = (
"/path/to/static", #collectstatic will find any app/static directories so do not add those here
)
By default it is empty.
Additionally, specify static files using href="{% static 'my-static.css' %}" instead of {{ STATIC_URL }}
You can also use findstatic to check if your static files are able to be located by the server.
Related
I'm hosting my site in railway. Everything is set up and works fine but the images uploaded by user don't load up.
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path. join(BASE_DIR,'media')
models.py
class Post(models.Model):
img = models.ImageField(upload_to="pics")
blog.html
{% extends 'base.html' %}
{% load static %}
{% static "images/projects" as baseUrl %}
{% for post in post_list %}
<div class="image_wrapper"><a href="{% url 'post_detail' post.slug %}" target="_parent"><img
src="{{ post.img.url }}" alt="image 1"/></a></div>
{% endfor %}
urls.py
urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root= settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Error I'm getting:
Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
instead of this:
src="{{ post.img.url }}"
Try this way:
src="/media/pics/post.img"
And in your models.py:
img = models.ImageField(upload_to="pics/") #Here added `forward slash (/)`
Try this way and see if it loads the image
files of whole project
I have correctly setup path for media url and still not able to find images in allproducts.html where as in categories.html it is able to find images from media directory. I am not able understand the cause of this bug.
allproducts.html
{% for sub in subcategory %}
{% for p in sub.product_set.all %}
<div class="product">
<div><h3 class="logo header_content d-flex flex-row align-items-center justify-content-start">{{sub.name}}</h3></div>
<div class="product_image"><img src="media/{{p.image}}" alt=""></div>
<div class="product_content">
<div class="product_title">{{p.name}}</div>
<div class="product_price">{{p.price}}</div>
</div>
</div>
{% endfor %}
<div></div>
{% endfor %}
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_DIR,
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
path('',views.index, name="index"),
path('cart',views.cart, name="cart"),
path('categories',views.categories, name="categories"),
path('checkout',views.checkout, name="checkout"),
path('contact',views.contact, name="contact"),
path('product/<int:pk>/',views.product, name="product"),
path('allproducts/<int:pk>/', views.allproducts, name="allproduct"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
def allproducts(request, pk):
products = Product.objects.all()
category = Category.objects.get(pk=pk)
subcategory = Subcategory.objects.filter(category = category)
return render(request, 'shop/allproducts.html',
{'products':products, 'subcategory':subcategory,
'category':category})
project files
kh
kh
.idea
__init__.py
settings.py
urls.py
wsgi.py
media
shop
images
test.jpg
shop
db.sqlite3
manage.py
You will certainly need a leading slash:
<img src="/media/{{p.image}}" alt="">
But better to let the image itself output its full path:
<img src="{{p.image.url}}" alt="">
I'm new to Django. Medial folder images are not displaying in Template file. please help me in that.
models.py
class Images(models.Model):
image = models. ImageField(upload_to='images', blank=True, null=True)
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
......
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
def image_display(request):
image_obj = Images.objects.all()
return render(request, 'index.html', {'image_obj': image_obj})
index.html
<body>
{% for item in myoffers_objs %}
<div>
<img src="{{ item.image.url }}" alt="Images"/>
</div>
{% endfor %}
</body>
Project details where i did mistake. why its displaying like this.
Image displaying like this
The for loop in the template file is incorrect.
Try this
<body>
{% for item in image_obj %}
<div>
<img src="{{ item.image.url }}" alt="Images"/>
</div>
{% endfor %}
</body>
correct static_root:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
you have to add this to your html file if you use statics in that html:
{% load staticfiles %}
also you have to run this command to collect static files in your project:
python manage.py collectstatic
I'm trying to display the media file(image) on the template of a DetailView.
I ran print statements to check where the MEDIA_ROOT and MEDIAFILES_DIRS are pointing, and they both point correctly to /project/static/media.
So I try to call it on the html page by using <img src="{{ object.profile_pic.url }}" /> , but it's not displaying.
I check the console, and it is looking for the file in XXX.X.X.X:8000/media/image_file.jpg.
Is it something to do with my MEDIA FILES setup in settings.py?
This is how my folder structure looks
/project
/project
/project
urls.py (base)
/apps
/app1
urls.py
manage.py
/static
/media
image_file.jpg
settings.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(os.path.dirname(BASE_DIR), "static", "static_files"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static_root")
"""
MEDIA FILES
"""
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
MEDIAFILES_DIRS = [
os.path.join(os.path.dirname(BASE_DIR), "static", "media"),
]
"""
Override the BaseUser model
"""
AUTH_USER_MODEL = 'accounts.User'
urls.py
// need to add the +static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to the base urls.py, not the app-level
from django.conf.urls import include, url
from django.contrib import admin
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.HomepageTemplateView.as_view(), name='home'),
url(r'^how-it-works/$', views.HowItWorksTemplateView.as_view(), name='how-it-works'),
url(r'^categories/', include('apps.categories.urls')),
url(r'^tasks/', include('apps.tasks.urls')),
url(r'^accounts/', include('apps.accounts.urls')),
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
detailview.html
{% extends 'base.html' %}
{% block navbar %}
<div class="row">
<div class="container">
{% include 'navbar.html' %}
</div>
</div>
{% endblock %}
{% block content %}
<div class="row">
<div class="container">
<div class="col-md-12">
{% load staticfiles %}
<p><img src="{{ object.profile_pic.url }}" /></p>
<p>{{ object.username }}</p>
<p>{{ object.first_name }} {{ object.last_name }}</p>
<p>{{ object.email }}</p>
<p>{{ object.contractorprofile.subcategory }}</p>
</div>
</div>
</div>
{% endblock %}
You added the static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) line to the urls.py of a specific app, i.e. not the base level urls.py. The base level will include the app-specific urls appending them to some stem. If the base urls.py has something like this, url(r'^apps/', include('apps.app1.urls')), then point your browser to server:8000/apps/media/image_file.jpg.
That's not what you want, so move the static() MEDIA_URL call to the base, project-level urls.py.
Let me mention a couple other things. Your folder structure puts media/ under static/; that's pretty confusing. You also included the settings for STATIC and MEDIA. Static files and media files are completely separate (often mixed up) topics. Static files are used by your code. Static files are the CSS, JavaScript, images, etc that your application needs. Media files are assets—images, documents, etc—that accrue through use of the application. profile_pic in your case is a perfect example of media; it's something a user uploaded. So nesting your media directory under static/ is conflating two independent things. Don't do it.
Another thing, you don't need {% load staticfiles %} in the template. That's used for staticfile-provided templatetags like {% static ...%} which you aren't using. Anyway, you should load templatetags at the top of the file to keep things clean.
Well I'm trying to use Bootstrap with Django by copying and pasting the folders from Bootstrap to static folder. But I'm not able to get access to the Bootstrap.css file. It shows 404 error.
Just for experimenting purpose, I created a main.css in the static/css folder and linked it in the template and to my surprise, its running.
So, why the bootstrap.css file is not getting linked.
Here is how I'm linking Bootstrap.css in my template
{% block css %}
<link rel="stylesheet" type="text/css" href="/static/css/bootstrap.css">
{% endblock %}
Here is my root urls.py
urlpatterns = patterns('',
(r'^',include('apps.home.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':os.path.normpath( os.path.join( os.path.dirname(__file__),'../static/'))}),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MEDIA_ROOT = 'C:/Users/Praful/uploads'
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
You should try this instead:
{% load static %}
{% block css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css ' %}">
{% endblock %}
...and just make sure you have 'django.contrib.staticfiles' in your INSTALLED_APPS. Please see also https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#template-tags
(EDIT: fixed typo, I oroginally forgot the "static" keyword)
OR this:
{% block css %}
<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/bootstrap.css">
{% endblock %}
..assuming "django.core.context_processors.media" is in your TEMPLATE_CONTEXT_PROCESSORS
Take a look at the faststart-bootstrap Django project skeleton with Bootstrap 3 support. However it's based on LESS style sheets, but LESS is easy to learn (in use) and compatible with CSS.
ok, that's a settings and path problem.
First, put that in your settings:
PROJECT_PATH = os.path.abspath(os.path.dirname(__name__))
MEDIA_ROOT = os.join(PROJECT_PATH, 'uploads')
MEDIA_URL = '/media/'
STATIC_ROOT = os.join(PROJECT_PATH, 'static')
STATIC_URL = '/static/'
And that in your template
{% block css %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/css/bootstrap.css">
{% endblock %}
Check your project structure. I follow this structure:
/Project_name
/App1
/App2
/App3
/Project_name
/media
/static
/css
bootstrap.min.css
/js
/templates
/Requirements
requirement.txt
.gitignore
With this structure and a proper settings and template files shown by lalo, bootstrap should be work without 404.