I have a problem when trying to display in a template a picture from my media file (for example a profil picture from an user). I have already looked at many topics, and everytime the answer is simply adding the line urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in the urls.py file. But I already have it and it still doesn't work. Here are the relevant part of my files :
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('actualites.urls')),
path('inscription/', include('inscription.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
views.py
def home(request):
return render(request, 'actualites/home.html', {'last_meals': Plat.objects.all()})
models.py
class Plat(models.Model):
titre = models.CharField(max_length = 100)
date = models.DateField(default=timezone.now, verbose_name="Date de préparation")
photo = models.ImageField(upload_to = "photos_plat/", blank = True)
class Meta:
verbose_name = "Plat"
ordering = ['date']
def __str__(self):
return self.titre
You can see that the pictures are recorded in the photos_plat directory, which is a subdirectory of the media directory.
the template :
{% extends "base.html" %}
{% block content %}
<h2>Bienvenue !</h2>
<p>
Voici la liste des plats disponibles :
</p>
{% for meal in last_meals %}
<div class="meal">
<h3>{{ meal.title }}</h3>
<img src="{{ meal.photo.url }}" height=512 width=512/>
<p>{{ meal.description|truncatewords_html:10 }}</p>
<p>Afficher le plat</p>
</div>
{% empty %}
<p>Aucun plat disponible.</p>
{% endfor %}
{% endblock %}
When I go the home page, I get the following error : ValueError at /
The 'photo' attribute has no file associated with it.
I have tried moving the pictures from the "photos_plat" directory directly to the media directory but that changes nothing.
I don't know what I did wrong, can someone help me please ?
Thanks in advance !
Related
I tried to upload image from the admin side in production but it doesn't shows up or stores in static/images but it used to work while working in local.
However my static images are loaded and also those I've saved in development are also showing up but while adding new images it doesn't get added to static files.
My model:
class Gallery(models.Model):
title = models.CharField(max_length=150)
image = models.ImageField(upload_to='images/',null=True,default="avatar.svg")
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
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('admin/', admin.site.urls),
path('', include('base.urls'))
]
urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
Gallery .html
{% for gallery in gallerys %}
<!-- ITEM 1 -->
<div class="col-xs-6 col-md-3">
<div class="box-gallery">
<a href="{{gallery.image.url}}" title="Gallery #1">
<img src="{{gallery.image.url}}" alt="" class="img-fluid" />
<div class="project-info">
<div class="project-icon">
<span class="fa fa-search"></span>
</div>
</div>
</a>
</div>
</div>
{% endfor %}
Settings.py
here i've uploaded only the required ones
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'base.NewUser'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static/")
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "/static/images")
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
views.py
def gallery(request):
gallerys = Gallery.objects.all()
context = {'gallerys':gallerys}
return render(request, 'base/gallery.html',context)
am i missing something here?
Thanks in advance
The way to store images in static folder.
Do this:
views.py:
def gallery(request):
if request.method == 'POST':
form = YourForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['image'])
model_instance = form.save()
model_instance.save()
else:
form = YourForm()
gallerys = Gallery.objects.all()
context = {'gallerys':gallerys}
return render(request, 'base/gallery.html',context)
def handle_uploaded_file(f):
with open('static/images/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
settings.py:
STATIC_URL = 'static/'
STATIC_ROOT=os.path.join(BASE_DIR,'static')
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('base.urls'))
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
This is the way that you can store static files.
I hope this may be get you
is there something wrong with my code? i already run makemigrations and migrate, and i can see the picture i saved on the admin site, but why when i try to call this picture on my html i received this error?
this is my html
{% for perfume in s %}
<img src="{{perfume.image.url}}" width="192px" height="192px" class="class">
{% endfor %}
my views.py
s = Perfume.objects.all()
....
my models.py
class Perfume(models.Model):
image = models.ImageField(upload_to='image',null=True, blank=True)
....
my settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
LOGIN_REDIRECT_URL = '/'
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
def get_success_url(self, request, user):
return (get_success_url)
my urls.py
urlpatterns = [
....
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your ImageField declared blank=True, null=True so image can be empty. You need to check if image has uploaded in your html.
{% for perfume in s %}
{% if perfume.image %}
<img src="{{ perfume.image.url }}">
{% endif %}
{% endfor %}
How can I display images from django models on tis page datat.ru/shop ?
I the source page code see <img class='img-fluid w-100' src="/media/images/2.png" alt="img" />
But only http://datat.ru/static/media/images/2.png returns image
How can I convert src="{{ shop.cover.url }}" to static/media/images/ ???
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('shop/', views.shop_list, name='shop'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
models.py
from django.conf import settings
from django.db import models
from django.utils import timezone
class Company(models.Model):
title = models.TextField()
cover = models.ImageField(upload_to='images/')
def __str__(self):
return self.title
shop_list.html
{% extends 'blog/base.html' %}
{% load staticfiles%}
{% block content %}
{% for shop in shops %}
<div class="container">
<div class="row">
<img class='img-fluid w-100' src="{{ shop.cover.url }}" alt="img" />
</div>
</div>
{% endfor %}
<!-- <img class="scale-with-grid" src="{{ shop.cover.url }}"/> -->
{% endblock %}
add this to settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/
and this to urls
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am developing a django app were i am uploading images through the admin panel
i have implemented this in my other apps but i can seem to get what is wrong with my configurations as follows
settings.py
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'ntakibariapp.Member'
LOGOUT_REDIRECT_URL = 'ntakimbari:_login'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('ntakibariapp.urls')),
path('accounts/', include('django.contrib.auth.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, ducument_root=settings.MEDIA_ROOT)
models.py
class Community_work(models.Model):
where = models.CharField(max_length=80)
time = models.TimeField(blank=False)
date = models.DateField(blank=False)
image_of_area = models.ImageField(upload_to='photos',blank=True)
post_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.where
template/communtity_work.html
{% extends 'temp/base.html' %}
{% block title %}community works{% endblock %}
{% block body %}
<div class="container">
{% for work in works %}
<p>Picture of the area <img src="{{work.image_of_area.url}}"></p>
<p>Where: {{work.where}}</p>
<p>Time: {{work.time}}</p>
<p>Date: {{work.date}}</p>
{% endfor %}
</div>
{% endblock %}
in urls.py you have a misspell try use
document_root
instead of ducument_root
Also shouldn't the tag be <img src="{{community_work.image_of_area.url}}">?
I'd like to add Imageform to my form to allow all users to add a photo.
I've read this https://docs.djangoproject.com/en/dev/ref/forms/fields/#imagefield
and this https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files
but still I'm confused about how to achieve that. How can I change my codes to allow users to add a photo from their own folders?Here's my codes and I also attached the ideal form I'd like to create.
[My ideal form]
models.py
from django.db import models
from django.forms import ModelForm
class Sell(models.Model):
subject = models.CharField(max_length=100)
price = models.CharField(max_length=100)
condition = models.CharField(max_length=100)
photo = models.ImageField(upload_to="media")
email = models.EmailField()
body = models.CharField(max_length=200)
forms.py
from django.forms import ModelForm
from uasite1.models import Sell
class SellForm(ModelForm):
class Meta:
model = Sell
views.py
from django.shortcuts import render_to_response,get_object_or_404
from django.http import HttpResponseRedirect
from uasite1.forms import SellForm
from uasite1.models import Sell
from django.template import RequestContext
def sell_create(request):
context = {}
if request.method == 'POST':
form = SellForm(request.POST)
if form.is_valid():
new_sell = form.save()
return HttpResponseRedirect('/sechand/%d/' % new_sell.pk)
else:
form = SellForm()
context['form'] = form
return render_to_response('sell.html',context,context_instance = RequestContext(request))
sell.html
{% extends 'base.html' %}
{% block extrahead %}
{% endblock %}
{% block content %}
<form enctype="multipart/form-data" action = "/sechand/" method = "post">
{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value="Submit" />
</form>
{% endblock%}
sell_display.html (this is the template where the submitted information would show up.)
{% extends 'base.html' %}
{% block content %}
<div id = 'sell'>
<h3> Product Name : [ {{ sell.subject }}]</h3>
<p>Photo{{ sell.photo }}</p>
<p>Price: [ {{ sell.price }} ]</p>
<p>Condition: [ {{ sell.condition }} ]</p>
<p>Comments: [ {{sell.body}} ]</p>
<p>Contact Email:[ {{ sell.email }} ]</p>
</div>
{% endblock %}
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^sechand/$','uasite1.views.sell_create'),
url(r'^sechand/(?P<pk>\d+)/$', 'uasite1.views.sell_detail'),
url(r'^products/electronics/$', 'uasite1.views.Electronics'),
url(r'^products/$', 'uasite1.views.ProductsAll'),
url(r'^admin/', include(admin.site.urls)),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I did not go through your entire code but I can notice 1 important mistake, view should have the following:
form = SellForm(request.POST, request.FILES)
Also, this line:
<p>Photo{{ sell.photo }}</p>
I don't think that's the way to show a photo, I would put a link to the photo doing:
<p>Photo{{ sell.photo.url }}</p>
And finally, for development environments you may want to serve media files so just add this line to your main urls.py file:
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
# your url patterns in here
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
editing:
Serving media files. That link should give you a good overview, it's confusing I know, so I am going to give you an example, just like I do in my projects. First the way I do it in settings.py:
#settings.py
from os.path import dirname, join, realpath
# have in mind that I have settings.py under project_root/project/settings.py
# so you probably want to check your path to your project root folder first
ROOT_DIR = realpath(join(dirname(__file__), '..'))
MEDIA_ROOT = realpath(join(ROOT_DIR, 'media'))
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
join(ROOT_DIR, "static"),
)
That's the way I do it, you could find many ways that also work. To give you a better clue my folders look like this:
project_root/
media/
static/
project/
settings.py