'image' attribute has no file associated with it - django - python

I have a blog project, and receive the above error when running the django dev server. I have uploaded an image via the admin panel, which then saves as expected in the posts/media folder. Please can anyone help?
My project (shortened version) looks as follows:
- blogproject
- posts
- media
- static
- templates
- posts
- base.html
- getAllPosts.html
- blog
- urls.py
- settings.py
- models.py
SETTINGS.PY
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [STATIC_DIR, ]
STATIC_URL = '/static/'
MEDIA_DIR = os.path.join(BASE_DIR, 'posts/media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
URLS.PY
[...]
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
models.py
class Post(models.Model):
title = models.CharField(max_length=200)
summary = models.CharField(max_length=500, default=True)
body = models.TextField()
pub_date = models.DateTimeField(default=timezone.now)
category = models.ManyToManyField('Category')
author = models.ForeignKey(User, default=True)
titleSlug = models.SlugField(blank=True)
authorSlug = models.SlugField(blank=True)
image = models.ImageField(upload_to="images/%Y/%m/%d", null=True)
def save(self, *args, **kwargs):
self.titleSlug = slugify(self.title)
self.authorSlug = slugify(self.author)
super(Post, self).save(*args, **kwargs)
def __str__(self):
return self.title
getAllPosts.html
<!DOCTYPE html>
{% extends "posts/base.html" %}
{% load static %}
{% load template_tags %}
{% block content %}
{% if latest_posts %}
{% for post in latest_posts %}
<a href="{% url 'getPost' slug=post.titleSlug %}">
<img src="{{ MEDIA.URL }} {{post.image.url}}" alt="image-
{{post.title}}"/>
</a>

Related

Django: problem of displaying uploaded images

I'm building a photo blog via Django, it has a very basic structure:
1)a list page: each post has a cover picture
2)severals detail pages correspondant: each page contains multiple pictures.
At the list page, things are all good, the cover picture displayed correctely, but for the detail web page, the pictures that I uploaded from django admin won't show up, though they can be found in the local folder \media. I checked the page in Chrome, I got this: <img src(unknown) alt>. I'm confused.
Thanks a lot for your time and help.
structure :
lyv_dev #project name
--settings.py
--urls.py
media
--upload1.jpg
--upload2.jpg
--upload3.jpg
-- ...
project #app name
-- templates
--projects
-- base.html
-- list.html
-- detail.html
-- urls.py
-- admin.py
-- views.py
static
-- css
-- style.css
db.sqlite3
manage.py
models.py
from django.db import models
from django.urls import reverse
# models project
class Project(models.Model):
title = models.CharField(max_length = 250)
slug = models.SlugField(max_length = 250, unique_for_date = 'publish')
text = models.TextField()
year = models.IntegerField(default = 2020)
# couv: this is a cover picture
couv = models.FileField(blank=True)
height = models.IntegerField(default=0)
weidth = models.IntegerField(default=0)
class Meta:
ordering = ('-publish', )
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('projects:project_detail', args=[self.slug])
# Images related with project
class ProjectImage(models.Model):
project = models.ForeignKey(Project, on_delete = models.CASCADE, related_name='projectimages')
images = models.FileField()
def __str__(self):
return self.project.title
admin.py
from django.contrib import admin
from .models import Project, ProjectImage
class ProjectImageAdmin(admin.TabularInline):
model = ProjectImage
#admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'publish', 'status')
list_filter = ('status', 'publish')
search_fields = ('title', 'text')
prepopulated_fields = {'slug':('title',)}
date_hierarchy = 'publish'
ordering = ('status', 'publish')
inlines = [ProjectImageAdmin]
class Meta:
model = Project
#admin.register(ProjectImage)
class PostImageAdmin(admin.ModelAdmin):
pass
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py (in django project folder)
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('projects.urls', namespace='projects')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
urls.py (in django app folder)
from django.urls import path
from .import views
from .views import ProjectLisView
app_name = 'projects'
urlpatterns = [
path('', ProjectLisView.as_view(), name='projects_list'),
path('projects/<slug:project>/', views.project_detail, name='project_detail'),
]
views.py
from django.shortcuts import render, get_object_or_404
from .models import Project, ProjectImage
from django.views.generic import ListView
class ProjectLisView(ListView):
model = Project
template_name = 'projects/list.html'
context_object_name = 'projects'
def project_detail(request, project):
project = get_object_or_404(Project, slug=project, status='published')
images = project.projectimages.all()
return render(request, 'projects/detail.html', {'project':project, 'images':images})
list.html
{% extends "projects/base.html" %}
{% block content %}
{% for project in projects %}
<p class="title">{{project.title}}</p>
<div><img src="{{ project.couv.url }}" alt=""></div>
{% endfor %}
{% endblock %}
detail.html
{% extends "projects/base.html" %}
{% block content %}
<p>this is a detail page</p>
{{ project.title }}
{{ project.year }}
<p>{{ project.width }} x {{ project.height }} mm </p>
{% for image in images %}
<div><img src="{{ images.url }}" alt=""></div>
{% endfor %}
{% endblock %}
base.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<section class="content">
{% block content %}
{% endblock %}
</section>
</body>
</html>

Image is not being accessed through port 8000(under development)

My image path is working but Idk why it's not able to display it, any help is appreciated
models.py
class movies(models.Model):
Image = models.ImageField(blank=True, null=True)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = 'media'
home.html
{% for m in movies %}
<img src="{{ m.Image.url }}" width="200px", height="300px">
{% endfor %}
class movies(models.Model):
Image = models.ImageField(upload_to='images/', blank=True, null=True)
So the problem was with the Media root, my path was fine but Django wasn't able to get it somehow, so I ran this code to automate Django to find media root by itself
ENV_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(ENV_PATH, 'media/')
and made a debug condition in the urls.py to run the request if viewed under development or localhost
if settings.DEBUG is True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Does not display an image! Django

Does not display an image!
image is exists, dut django didn't display any images on page, how to fix this?
this is my models.py
class All_Images_Of_The_Series(models.Model):
to_series = models.ForeignKey(Series, on_delete=models.CASCADE, blank=True, default=None)
image_of_all = models.ImageField(upload_to="previews/previews_for_series/", default=None,width_field="width_field", height_field="height_field")
is_poster = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return "Active: |%s| and Poster: |%s| " % (self.is_active, self.is_poster)
class Meta:
ordering = ["-timestamp"]
verbose_name = 'All_Images_of_the_Series'
verbose_name_plural = 'All_Images_of_the_Series'
this is my views.py
def homeview(request, *args, **kwargs):
full_path = All_Images_Of_The_Series.objects.all()
context = {"full_path":full_path,}
return render(request, 'home.html', context)
this is my template
<div class="col-sm-3 right-side">
<div class="new-movies-block">
<a class="header" href="#/new/">
<div class="title">Новинки</div>
</a>
{% for one_to_one_path in full_path %}
<div class="movie-spacer" ></div>
<a class="new-movie" href="{{ one_to_one_path.to_series.get_absolute_url }}" title="{{ one_to_one_path.to_series.eng_name }}">
<div class="title-info">
{{ one_to_one_path.to_series.season_of_this_series.number_of_season }} сезон {{ one_to_one_path.to_series.number_of_series }} серия
</div>
<div class="date">{{ one_to_one_path.to_series.timestamp_rus }}</div>
<img src="{{ one_to_one_path.image_of_all.url }}" class="img-responsive">
</a>
{% endfor %}
</div>
</div>
If you look at the element code, the images, then in the line "src" there is a path to the picture, and it's working! But does not display the picture itself!
<img src="/media/previews/previews_for_series/1.png" class="img-responsive">
this is error in console(f12)
GET http://127.0.0.1:8000/media/previews/previews_for_series/1.png 404 (Not Found)
Do this !
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^series/', include("serials.urls", namespace='series')),
url(r'^', include("serials.urls", namespace='homeview')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
just a quick thoughts, you don't show me the things you might need to work. For example if this if for development on the urls you need this https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-files-uploaded-by-a-user-during-development and on your settings you may need something like that
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
I hope it helps
Best
Perhaps you haven't added the media to your urls.py
From django.conf import settings
# your stuff
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT
})
)

Serving Static Images from Application in Django

I am following a Django book which builds a web application. When I build a template, I get the same result as that of the book, except for my images - they are not there.
I am wondering what can be causing this issue. The images have correct URL's but when I try to open them, Django states "Page NOT found 404".
I am pasting the relevant code below. In addition, I include a screenshot of my directory tree.
shop/models.py:
class Product(models.Model):
category = models.ForeignKey(Category,
related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d',
blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
template:
<a href="{{ product.get_absolute_url }}">
<img src=" {% if product.image %}
{{ product.image.url }}
{%else %}
{% static 'img/no_image.png' %}
{% endif %}
">
</a>
views.py
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request, 'shop/product/list.html',
{'category': category,
'categories': categories,
'products': products})
Edit (settings.py and urls.py):
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^shop/', include('shop.urls', namespace='shop')),
url(r'^cart/', include('cart.urls', namespace='cart')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)

ImproperlyConfigured at / - /static/ isn't a storage module

I am trying to upload a file.
this is my model.
def custom_path(instance, filename):
return '/'.join(['upload',instance.student.user.username,filename])
class Doc(models.Model):
uploadtime = models.DateTimeField(auto_now_add=True, blank=True)
datei = models.FileField(upload_to=custom_path,default='')
student = models.ForeignKey(Student,related_name='students_file')
title = models.TextField()
desc = models.TextField()
def __unicode__(self):
return self.title
and this is my views.py
def hochgeladen_danke(request):
if request.FILES.get('file'):
student = request.user.get_profile()
student.students_file.create(datei=request.FILES.get('file'),title='t',desc='t')
return render_to_response('upload.html',{},context_instance=RequestContext(request))
my html:
<form action="/hochgeladen_danke/" method="post" enctype="multipart/form-data">
{% csrf_token %}
File: <input type="file" name="file"/>
<button type="submit">upload</button>
</form>
my settings.py:
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media")
MEDIA_URL = "/media/"
STATIC_ROOT = os.path.join(PROJECT_PATH, "static")
STATIC_URL = '/static/'
when i try to upload a file. it is saying:
ImproperlyConfigured at /hochgeladen_danke/
/static/ isn't a storage module.
i dont know why this is happening. my custom_path seems to be right.
my urls.py:
..
url(r'^hochgeladen_danke/$','hochgeladen_danke',name='hochgeladen_danke'),
)
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns
Something is wrong with your settings.DEFAULT_FILE_STORAGE.
The exception you have provided comes from django.core.files.storage#272, which in turn comes from default_storage right below, and django.db.models.files#221. The constructor is called in your view, causing the exception to be thrown.

Categories