I am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for gallery images with a filefield), the image is stored in /media/images correctly. I have my media settings set in settings.py as follows:
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
Project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
import gallery.views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('gallery.urls')),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Gallery urls.py:
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^', views.homepage, name = 'home'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Gallery views.py:
def homepage(request):
texts = Sitetext.objects.all()
gal = Galleryimg.objects.all()
gal.order_by('position')
return render(request,'index.html', {"text1":texts[0].text,"text2":texts[1].text,"text3":texts[2].text,"text4":texts[3].text,"title1":texts[0].title,"title2":texts[1].title,"title3":texts[2].title,"title4":texts[3].title,"gallery":gal})
And then this is the part of the template code that accesses the image:
{% for g in gallery %}
<div class="col-md-3 col-sm-4 col-xs-6">
<img class="img-responsive" src="g.imgfile.url" />
</div>
{% endfor %}
When I create a gallery image, a broken image pops up, but the image is not accessed correctly.
I do this and I am able to serve media files from the Django development server:
urlpatterns += [
url(r'^media/(?P<path>.*)$', django.views.static.serve, {
'document_root': settings.MEDIA_ROOT}),]
It should be enough to include that just in the project urls.py.
The issue with yours could be that your media URL entry in urls.py is not correct. You seem to be not matching the actual URL of the media file, which is probably something like /media/something.png. You seem to be just qualifying on /media/. I also think your regex should be ^media/, not /media/.
Remove the static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) part, from your gallery.urls file.
Replace src="g.imgfile.url" with src="{{ g.imgfile.url }}".
Aside question: Why do you pass this big dictionary ({"text1":texts[0].text,...) to your template? It is error prone and bad practice. You should just pass 'texts': texts and inside your template iterate over them with a {% for text in texts %} forloop. So, the render method should be something like render(request, 'index.html', {'texts': texts, 'gallery': gal}).
Related
A beginner building a personal blog. Got a simple model with an ImageField. No matter what I try the Django won't serve an image.
Judging by the console output in the Dev Tools it is looking for an image in the wrong folder. I don't know how to fix that. I tried setting up MEDIA_URL, MEDIA_ROOT and adding a urlpattern like it's being suggest here and here
I have uploaded the picture via admin panel, its location is media/images/stockmarket.jpg. But for some reason the server is looking for an image here /blog/images/stockmarket.jpg
Project name: 'wikb', 'blog' is an App:
project_file_system
models.py
from django.db import models
class Post(models.Model):
title = models.CharField('Post Title', max_length=200)
preview = models.CharField('Post Preview', max_length=400)
thumbnail = models.ImageField('Post Picture', upload_to='images/', blank=True)
view.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Post
def home(request):
all_posts = Post.objects.all()
hero_post = all_posts[0]
context = {'hero_post': hero_post, 'all_posts': all_posts}
return render(request, 'blog/home.html', context=context)
HTML
<div class="hero">
<a href="#" class="hero__link" style="background-image: url({{hero_post.thumbnail}})">
<article class="hero__article">
<h2 class="hero__heading">{{hero_post.title}}</h2>
<p class="hero__preview">{{hero_post.preview}}</p>
</article>
</a>
</div>
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
Global urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('blog/', include('blog.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It's my first Django project, please explain like I'm 5.
Update: I forgot to add .url when I referenced an object in templates.
In templates, you'll want to use .url to get the real URL of a FieldFile (the file contained by a FileField or ImageField):
<a href="#" class="hero__link" style="background-image: url({{ hero_post.thumbnail.url }})">
I am trying to add upload image to admin form in my Django project I found on GitHub. I can upload image to folder my_app(catalog)/media/images/image.png but when I try to call it in the template I can only see that image icon that appears when there is no picture.
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'catalog/media')
model.py
class Book(models.Model):
image = models.ImageField(blank=True, null = True, upload_to='images')
book_detail.html
img src="{{ book.image.url}}" width="250"
views.py
class BookDetailView(generic.DetailView):
model = Book
urls.py
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', views.index, name='index'),
path('book/create/', views.BookCreate.as_view(), name='book_create'),
path('books/', views.BookListView.as_view(), name='books'),
path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is how it looks like (I print {{ book.image }} next to the picture (images/screenshot_4.png):
This is the error I get:
You may have dropped a ']' at the end of your urlpatterns or maybe I am mistaken
Ok I found out after spending way to much time on it.
img src="{{ book.image.url}}" width="250" line in template should look like
img src="../media/{{ book.image.url}}" width="250".
Hope this helps someone with the same problem.
I dont know why image is not display on the home page. Please see my code. I am on windows running python3 and Django 2.1. Is there any setting need to be done in files somewhere in Django folders like any config file? Please guide
Settting File:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
URL file:
from django.contrib import admin
from django.urls import path
from django.urls import include, path
import jobs.views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('home', jobs.views.home, name='home'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Model File
from django.db import models
# Create your models here.
class Job(models.Model):
image = models.ImageField(upload_to='images/')
summary = models.CharField(max_length=300)
Home Page File
<html lang="en">
{% load static %}
<head>
And where I want to show the image is end of a div
<img src="{% static '9.jpg' %}" height="200"></img>
</div>
</section>
In settings.py you will need to add settings for MEDIA_ROOT and MEDIA_URL. That is what the ImageFile upload_to relates to. See the documentation here.
You can then for example reference the image in the home page template as follows:
<img src="{{ '/media/images/9.jpg' }}">
http://127.0.0.1:8000/accounts/login/
This page is created successfully and working nice:
And Problem with these pages: http://127.0.0.1:8000/accounts/logout/ This page redirect me Django Administration Pages that message to login again but I don't want this.
I have placed my HTML file in
..templates/registration/logged_out.html
And checked spelling error multiple time to see why not working.
My urls files:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('catalog.urls')),
path('accounts/', include('django.contrib.auth.urls')),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
and my logged_out.html is:
{% extends 'base.html' %}
{% block content %}
<p>Logged out!</p>
Click here to login again.
{% endblock %}
Can any tell me what's wrong with it? How to fix this?
If you have defined LOGOUT_REDIRECT_URL in your settings, then LogoutView will redirect to it.
Check to see if you have defined LOGOUT_REDIRECT_URL in your settings, and remove it if you have.
I am following the Django 1.6 tutorial on how to work with static files (https://docs.djangoproject.com/en/1.6/howto/static-files/). However, something is not working...
This is what I have so far...
URLS:
#mysite/urls.py:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^myapp/', include('myapp.urls')),
)
#mysite/myapp/urls.py:
from django.conf.urls import patterns, include, url
from myapp import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)
VIEWS:
#mysite/myapp/views.py:
from django.shortcuts import render
def index(request):
return render(request, 'myapp/index.html')
TEMPLATES:
#mysite/myapp/templates/myapp/index.html:
{% load staticfiles %}
<img src="{% static "myapp/image1.jpg" %}" alt="Image 1"/>
In the mysite/settings.py file, I have STATIC_URL = '/static/'. In the folder mysite/myapp/static/myapp, I have a file named image1.jpg.
When I run the development server, it runs fine if I just put some other HTML in my index.html file, but when I try to display the image as above, it just shows a little white box where the image should be. Furthermore, if I go to localhost:8000/myapp/static/myapp/image1.jpg, I get a 404 error.
I'm assuming I'm doing something very obviously wrong...but what is it?
One thing - the STATIC_URL in settings.py is relative to the app directory, not the project directory, right?
Thank you!
When you're running in production, your static files are managed by the server (Apache, nginx) however when your DEBUG is set to true in your settings.py you'll have to tell django to serve the static files for you. To do this add the following to your URLs.py:
from django.conf import settings
(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_ROOT}),
This will allow static to be searchable and serve your static files.
img src="{% static 'myapp/image1.jpg' %}" alt="Image 1"/>