Using image in a template django - django

I want to view images, in a template, but I don't understand what I'm doing wrong.
models.py
class Item(models.Model):
name = models.CharField(verbose_name = "Название", max_length = 100)
TYPE_ITEMS = (
("shirt", "Футболка"),
("shoes", "Обувь"),
("bags", "Рюкзаки и сумки"),
("heads", "Головные уборы"),
("others", "Другое"),
)
type_item = models.CharField(verbose_name = "Тип продукта",
choices = TYPE_ITEMS, max_length = 6,
default = "shirt")
other = models.CharField("другая информация", max_length = 200)
color = models.CharField("Цвет(а)", max_length = 100)
cost = models.IntegerField("Стоимость за штуку", default = 0)
is_available_now = models.BooleanField("Есть ли в наличии?",
default = False)
available_count = models.IntegerField("Количество в наличии", default = 0)
photo = models.ImageField("Фото", upload_to = "photos/to_trade")
def __str__(self):
return self.name + " " + self.color + " (" + str(self.cost) + " грн)"
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader ####
from myapp.models import Item
def index(request):
return render(request, "index.html")
def goods(request):
shirts_list = Item.objects.filter(type_item = "shirt")
template = loader.get_template("goods.html")
context = RequestContext(request, {
"shirts_list": shirts_list,})
return HttpResponse(template.render(context))
def contacts(request):
return render(request, "contacts.html")
def delivery(request):
return render(request, "delivery.html")
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from myapp import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'paporotnik.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.index, name = "index"),
url(r'^goods', views.goods, name = "goods"),
url(r'^contacts', views.contacts, name = "contacts"),
url(r'^delivery', views.delivery, name = "delivery"),
url(r'^photos/to_trade/(?P<path>.*)$', 'django.views.static.serve'),
)
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = '(=bk#zukikdq==0dtokjbg-sbgge5zi(^te01+9=w%is-76sxv'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = [os.path.join(BASE_DIR, "templates")]
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'paporotnik.urls'
WSGI_APPLICATION = 'paporotnik.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = "C:\\Python33\\Scripts\\paporotnik\\static"
This is my template:
{% load staticfiles %}
<!DOCTYPE HTML>
<html>
<head>
<meta charset = "utf-8">
<title>Товары - Paporotnik.ua</title>
<link rel = "stylesheet", type = "text/css", href = "{% static 'myapp/style_index.css' %}">
</head>
<body>
<div id="container">
<!-- Верхняя панель (заголовок) -->
<div id="header">
<div style = "float: left; width:100%">
<div style = "margin: 0 10%;">
<br><h1 id = "heed">Paporotnik.ua</h1><br>
</div>
</div>
<div id = "divLogo">
<img id = "logo", width = "125", height = "125">
</div>
<div id = "trash" align = "center">
<h3>Корзина</h3>
<img align = "center", width = "70", height = "50">
</div>
</div>
<!-- Центр, основное содержимое -->
<div id="wrapper">
<div id="content">
<p align = "center">
<h2 align = "center">Футболки</h2>
<div align = "center">
{% for item in shirts_list %}
<img src = "{{item.photo}}", width = "150", height = "250">
{% endfor %}
</div>
</div>
</div>
</div>
</body>
</html>
When I view the code in a browser, the path is correct:
But when I click on the URL, I see this:
It tells me that my picture doesn't exist, but it is there!

Something that I would like to bring to your notice. static stores your css,js and images that are needed for the website frontend. media stores all the images uploaded by the user. So, in your settings define,
MEDIA_URL = 'media/'
Then, inside your template append /{{MEDIA_URL}} in front of {{item.photo}}.
And in your urls.py file, to the urlpatterns append:
+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This ought to sort the problem.

You are not specifying the URL of the photo correctly. In your template, replace the line
<img src = "{{item.photo}}", width = "150", height = "250">
with
<img src = "{{item.photo.url}}", width = "150", height = "250">

I think you haven't specified a media folder. In your settings.py you need this:
MEDIA_URL = '/media/'
MEDIA_ROOT = join(settings.PROJECT_ROOT, 'media')
And photos/to_trade should be inside this media folder. Also you need to use {{item.photo.url}} in your template instead of {{item.photo}}

Related

got error while setting default image in ImageField Django

my model have an imagefield which stores the image for post . I want to add default image to that in case if not is not uploaded.But I am getting error The 'title_image' attribute has no file associated with it. If I upload image then its working fine.
Models.py
class Post(models.Model):
title_image = models.ImageField(
upload_to='Images/PostTitleImages/',
max_length=None,
default = 'Images/Image_not_found.jpg',
blank = True,
null = True)
home.html
<img src="{{post.title_image.url}}" height="350px"/>
Settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/'),
]
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('MainSite.urls'), name = "Main"),
path('account/',include('account.urls'), name = 'Accounts')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
what I am doing wrong here I checked the file is in this directory /media/Images/PostTitleImages/
In case of media you need to include the media tag in your template like so:
# template
<img src="{{ media_url }}{{ post.title_image.url }}>
and in your settings add the context processor
# settings.py
'django.template.context_processors.media'

super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'label'

I tried a multi-select-field project in Django. Based on my knowledge everything is correct. But, try to make migrations it shows TypeError. How to fix it?
Error
File "D:\My Django Projects\multiselectproject\multiselectapp\forms.py", line 4, in <module>
class EnquiryForm(forms.Form):
File "D:\My Django Projects\multiselectproject\multiselectapp\forms.py", line 30, in EnquiryForm
course = MultiSelectField(label='Select Required Courses:', choices='Courses_Choices')
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\multiselectfield\db\fields.py", line 70, in __init__
super(MultiSelectField, self).__init__(*args, **kwargs)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 986, in __init__
super().__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'label'
settings.py
"""
Django settings for multiselectproject project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'n&*##g^b-%-$-yd1^!iwzhfnttd4s^zf+&$*5!i0_ves1v8s4&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'multiselectapp.apps.MultiselectappConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'multiselectproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'multiselectproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'multiselectdb',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'root',
}
}
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
# }
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
models.py
from django.db import models
from multiselectfield import MultiSelectField
# Create your models here.
class EnquiryData(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(max_length=20)
mobile = models.IntegerField()
Courses_Choices = (('Python', 'Python'), ('Django', 'Django'), ('Flask', 'Flask'), ('Rest API', 'Rest API'), ('UI', 'UI'))
course = MultiSelectField(max_length=200, choices='Courses_Choices')
Locations_Choices = (('Hyd', 'Hyderabad'), ('Bang', 'Banglore'), ('Che', 'Chennai'), ('Mum', 'Mumbai'))
locations = MultiSelectField(max_length=200, choices='Locations_Choices')
Trainers_Choices = (('Govardhan', 'Govardhan'), ('Manikanta', 'Manikanta'), ('Kartheek', 'Kartheek'))
trainers = MultiSelectField(max_length=200, choices='Trainers_Choices')
gender = models.CharField(max_length=20)
start_date = models.DateField(max_length=50)
forms.py
from django import forms
from multiselectfield import MultiSelectField
class EnquiryForm(forms.Form):
name = forms.CharField( label = 'Enter your name:', widget = forms.TextInput(
attrs = {
'class':'form-control',
'placeholder':'Your name'
}
)
)
email = forms.EmailField( label = 'Enter your email:', widget = forms.EmailInput(
attrs = {
'class':'form-control',
'placeholder':'Your email'
}
)
)
mobile = forms.IntegerField( label = 'Enter your contact number:', widget = forms.NumberInput(
attrs = {
'class':'form-control',
'placeholder':'Your contact number'
}
)
)
Courses_Choices = (('Python', 'Python'), ('Django', 'Django'), ('Flask', 'Flask'), ('Rest API', 'Rest API'), ('UI', 'UI'))
course = MultiSelectField(label='Select Required Courses:', choices='Courses_Choices')
Locations_Choices = (('Hyd', 'Hyderabad'), ('Bang', 'Banglore'), ('Che', 'Chennai'), ('Mum', 'Mumbai'))
locations = MultiSelectField(label='Select Required Locations', choices='Locations_Choices')
Trainers_Choices = (('Govardhan', 'Govardhan'), ('Manikanta', 'Manikanta'), ('Kartheek', 'Kartheek'))
trainers = MultiSelectField(label='Select Required Trainers', choices='Trainers_Choices')
Gender_Choices = (('Male', 'Male'), ('Female', 'Female'))
gender = forms.ChoiceField(widget=forms.RadioSelect, choices='Gender_Choices', label='Select your gender')
start_date = forms.DateField(widget=forms.SelectDateWidget(), label='Select your timings')
views.py
from django.shortcuts import render
from .models import EnquiryData
from .forms import EnquiryForm
# Create your views here.
def enquiry_view(request):
if request.method == 'POST':
pass
else:
form = EnquiryForm()
context = {'form':form}
return render(request, 'enquiry.html', context)
enquiry.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="container">
<div class="row">
<div class="offset-md-3 col-md-6">
<form>
{% csrf_token %}
{{ form }}
<input type="submit" name="submit" value="Save">
<input type="reset" name="reset" value="Cancel">
</form>
</div>
</div>
</div>
</body>
</html>
urls.py-multiselectapp
from django.urls import path
from multiselectapp import views
urlpatterns = [
path('', views.enquiry_view, name=''),
]
urls.py
"""multiselectproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('multiselectapp.urls')),
]
For a form field, you use the MultiSelectFormField, not a MultiSelectField:
from django import forms
from multiselectfield.forms.fields import MultiSelectFormField
class EnquiryForm(forms.Form):
# …
Courses_Choices = (
('Python', 'Python')
, ('Django', 'Django')
, ('Flask', 'Flask')
, ('Rest API', 'Rest API')
, ('UI', 'UI')
)
course = MultiSelectFormField(label='Select Required Courses:', choices='Courses_Choices')
Locations_Choices = (
('Hyd', 'Hyderabad')
, ('Bang', 'Banglore')
, ('Che', 'Chennai')
, ('Mum', 'Mumbai')
)
locations = MultiSelectFormField(label='Select Required Locations', choices='Locations_Choices')
Trainers_Choices = (
('Govardhan', 'Govardhan')
, ('Manikanta', 'Manikanta')
, ('Kartheek', 'Kartheek')
)
trainers = MultiSelectFormField(label='Select Required Trainers', choices='Trainers_Choices')
That being said, if you work with a ModelForm, Django can already do most of the work for you.

Image from database is not displayed in django template

I am trying to store images in database via form ImageField of model which gets uploaded to media folder that i have created and render the same in template.
This is my folder structure-
folder structure
This is my settings.py file-
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
MEDIA_DIR = os.path.join(BASE_DIR,'media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '9q5awt($2rn+iwvku6p!r59st5a#g^%oqcc16=*v9s&-q_7=+n'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'userAuth',
'groups',
'posts',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_ROOT=MEDIA_DIR
MEDIA_URL='/media/'
LOGIN_REDIRECT_URL = "/loggedin"
LOGOUT_REDIRECT_URL = "/loggedout"
This is my post app's urls.py file. Just to inform, I have 3 apps namely posts,groups,userAuth.
from django.conf.urls import url
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
app_name='posts'
urlpatterns = [
url(r"^$", views.PostList.as_view(), name="all"),
url(r"new/in/(?P<pk>\d+)/$", views.CreatePost.as_view(), name="create1"),
url(r"comment/in/(?P<pk>\d+)/$", views.CreateComment.as_view(), name="create2"),
url(r"by/(?P<username>[-\w]+)/$",views.UserPosts.as_view(),name="for_user"),
url(r"by/(?P<username>[-\w]+)/(?P<pk>\d+)/$",views.PostDetail.as_view(),name="single"),
url(r"comment/delete/(?P<pk>\d+)/$",views.DeleteComment.as_view(),name="delete_comment"),
url(r"delete/(?P<pk>\d+)/$",views.DeletePost.as_view(),name="delete"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
This is post_detail.html, the template in which i am trying to render images(line 8) -
{% extends "posts/post_base.html" %}
{% block content %}
<div class="col-md-8">
<div class="post media ">
<div class="post media list-group-item" style="margin-top: 9px;"><h3 class="title list-group-item-heading" style="color: black !important; margin-bottom: 10px;font-size: large;">{{ post.question }}</h3></div>
<div class="post media list-group-item" style="margin-top: 9px;"><h3 class="title list-group-item-heading" style="color: black !important; margin-bottom: 10px !important; font-size: medium;">{{ post.description_html|safe }}</h3></div>
///line 8 <img src="{{MEDIA_URL}}/pics/{{ post.picture }}" class="img-responsive" style="width: 100%; float: left; margin-right: 10px;" alt="heyy"/>
<div class="media-body">
<h5 class="media-heading" style="margin-top: 7px;">
<span class="username">#{{ post.user.username }}</span>
<time class="time">{{ post.created_at }}</time>
</h5>
the uploading part works perfectly as i got pics/download.jpg on printing {{ post.picture }} on the template instead of line 8
This is my models.py of posts app-
from django.conf import settings
from django.urls import reverse
from django.db import models
import misaka
from groups.models import Group
from django.contrib.auth import get_user_model
User = get_user_model()
class Post(models.Model):
user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
question = models.CharField(max_length=255)
# question_html = models.TextField(editable=False)
description=models.TextField(blank=True, default='')
description_html = models.TextField(editable=False)
picture=models.ImageField(upload_to='pics',blank=True)
group = models.ForeignKey(Group, related_name="posts",null=True, blank=True,on_delete=models.CASCADE,)
def __str__(self):
return self.question
def save(self, *args, **kwargs):
self.question_html = misaka.html(self.question)
self.description_html = misaka.html(self.description)
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse(
"posts:single",
kwargs={
"username": self.user.username,
"pk": self.pk
}
)
class Meta:
ordering = ["-created_at"]
unique_together = ["user", "question"]
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments',on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
comment = models.TextField()
text_html = models.TextField(editable=False)
user = models.ForeignKey(User, related_name="comments",on_delete=models.CASCADE)
def save(self, *args, **kwargs):
self.text_html = misaka.html(self.comment)
super().save(*args, **kwargs)
def get_absolute_url(self):
# return reverse("posts:single" , kwargs={"slug": self.slug})
return reverse("posts:single" , kwargs={"username":self.post.user.username,"pk":self.post.pk})
def __str__(self):
return self.text
forms.py of posts app-
from django import forms
from posts import models
class PostForm(forms.ModelForm):
class Meta:
# fields = ("message", "group")
fields = ('question','description','picture')
model = models.Post
class CommentForm(forms.ModelForm):
class Meta:
# fields = ("message", "group")
fields = ('comment',)
model = models.Comment
This is m webpage on rendering, also for reference i opened the elements on inspecting which shows different url -
webpage
I am getting the broken image and alt text instead of actual image.

Image Doesn't display in django from sqlite3 databbase

I am creating a website that should display several images, but none is displayed.
I have tried several ways to solve it but no changes,
image's URL is saved in sqlite db
views.py
def add_story(request):
if request.method == "POST":
form = StoryCreate(request.POST, request.FILES)
if form.is_valid():
storyitem = form.save(commit=False)
storyitem.save()
else:
form = StoryCreate()
return render(request, 'story_form.html', {'form':form})
urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root= settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(SITE_ROOT, 'statics')
MEDIA_URL = '/media/'
html
<img name="Story" style="height: 100px; width: 100px" src="{{item.LogoUrl.url}}"/>

How to render image in my Django Blog Template?

Hi Guys I have a blog setup and I want to add the ability for an image or thumbnail to be included in every blog post. I'm having trouble getting the location of the file and the blog template to match up and show the image. I'm also having difficulties integrating the ImageWithThumbnail model to the Entry model.
post.html
{% include 'head.html' %}
{% include 'navbar.html' %}
{% load staticfiles %}
{% load django_markdown %}
<div class="container">
<div class="post">
<h2>{{ object.title }}</h2>
<p class="meta">
{{ object.created }} |
Tagged under {{ object.tags.all|join:", " }} <p> Created by
{{ object.author }} </p>
</p>
{{ object.body|markdown }}
<img src="{% static "{{ STATIC_ROOT }}/media/tableau_public.jpg" %}" alt="My image"/>
{{ object.file }}
</div>
{% include 'footer.html' %}
Settings.py
"""
Django settings for vizualytic project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#ic_*)dw$fxp+p_c=3e=91ujzivxurqf7y7572z9&sfs19aek%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_markdown',
'website',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'vizualytic.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(BASE_DIR), "static", "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'vizualytic.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "static"),
)
view.py
from django.views import generic
from . import models
class BlogIndex(generic.ListView):
queryset = models.Entry.objects.published()
template_name = "blog.html"
paginate_by = 3
class BlogDetail(generic.DetailView):
model = models.Entry
template_name = "post.html"
models.py
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
class Tag(models.Model):
slug = models.SlugField(max_length=200, unique=True)
def __str__(self):
return self.slug
class EntryQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
class Entry(models.Model):
title = models.CharField(max_length=200)
name = models.CharField(max_length = 255)
file = models.ImageField()
thumbnail = models.ImageField(upload_to=settings.MEDIA_ROOT+"/%Y/%m/%d",max_length=500,blank=True,null=True)
author = models.CharField(max_length=200, null=True)
body = models.TextField()
slug = models.SlugField(max_length=200, unique=True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
objects = EntryQuerySet.as_manager()
def filename(self):
return os.path.basename(self.file.name)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("entry_detail", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
class ImageWithThumbnail(models.Model):
name = models.CharField(max_length = 255)
image = models.ImageField(upload_to="/%Y/%m/%d",max_length=500,blank=True,null=True)
thumbnail = models.ImageField(upload_to="/%Y/%m/%d",max_length=500,blank=True,null=True)
def create_thumbnail(self):
# original code for this method came from
# http://snipt.net/danfreak/generate-thumbnails-in-django-with-pil/
# If there is no image associated with this.
# do not create thumbnail
if not self.image:
return
from PIL import Image
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
import os
# Set our max thumbnail size in a tuple (max width, max height)
THUMBNAIL_SIZE = (200,200)
DJANGO_TYPE = self.image.file.content_type
if DJANGO_TYPE == 'image/jpeg':
PIL_TYPE = 'jpeg'
FILE_EXTENSION = 'jpg'
elif DJANGO_TYPE == 'image/png':
PIL_TYPE = 'png'
FILE_EXTENSION = 'png'
# Open original photo which we want to thumbnail using PIL's Image
image = Image.open(StringIO(self.image.read()))
# Convert to RGB if necessary
# Thanks to Limodou on DjangoSnippets.org
# http://www.djangosnippets.org/snippets/20/
#
# I commented this part since it messes up my png files
#
#if image.mode not in ('L', 'RGB'):
# image = image.convert('RGB')
# We use our PIL Image object to create the thumbnail, which already
# has a thumbnail() convenience method that contrains proportions.
# Additionally, we use Image.ANTIALIAS to make the image look better.
# Without antialiasing the image pattern artifacts may result.
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
# Save the thumbnail
temp_handle = StringIO()
image.save(temp_handle, PIL_TYPE)
temp_handle.seek(0)
# Save image to a SimpleUploadedFile which can be saved into
# ImageField
suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
temp_handle.read(), content_type=DJANGO_TYPE)
# Save SimpleUploadedFile into image field
self.thumbnail.save('%s_thumbnail.%s'%(os.path.splitext(suf.name)[0],FILE_EXTENSION), suf, save=False)
def save(self):
# create a thumbnail
self.create_thumbnail()
super(ImageWithThumbnail, self).save()
Any help would be greatly appreciated.
Thanks
you just need:
<img src="{{ object.thumbnail.url }}" alt="My image"/>
note that the {% static 'file.extension' %} is used only to render static files.
I would suggest to use Django Filer with Easy Thumbnails.
You will only need one image field in your model and leave making the thumbnail to Easy Thumbnails on rendering of the template.