How to render image in my Django Blog Template? - django

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.

Related

Django Files Upload from Form get CSRF Forbidden on production

I have a simple Django FileForm for multiple files upload (basically txts with polygon coordinates). I don't want to save the uploaded files anywhere but only treat them on the fly (memory?) and return a leaflet map with the polygons and a new file of mine (which transforms and exports all the txts in a .dxf format file (CAD combatible)).
I have done all the logic and my programm seems to work fine on development but on production (Heroku) when i hit the submit button on my form I keep getting CSRF Forbidden 403 message. I am really frustrated. I have used csfr decorators (csrf_exempt, requires_csrf_token, ensure_csrf_cookie) on my views but none seems to work. I have included
enctype="multipart/form-data"> and {% csrf_token %} on my form template.
What's the problem? It's hard for me to test and try because on development everything is ok and I have to deploy everytime only to see if another approach works.
Is it because I am not saving the files on a model and on a disk (What's the logic here?), or is it because I'm missing something on the CSRF part on my settings?
settings.py (when deploying)
"""
Django settings for myKAEK project.
Generated by 'django-admin startproject' using Django 4.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
from decouple import config
from decouple import config, Csv
# 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/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'mykaek-gr.herokuapp.com', 'myKAEK.gr', 'www.myKAEK.gr']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'djgeojson',
'storages',
'debug_toolbar',
'myKAEKapp',
]
MIDDLEWARE = [
"debug_toolbar.middleware.DebugToolbarMiddleware",
'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',
]
INTERNAL_IPS = [
"127.0.0.1",
]
ROOT_URLCONF = 'myKAEK.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'myKAEK.wsgi.application'
GOOGLE_MAPS_API = config('GOOGLE_MAPS_API')
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.contrib.gis.db.backends.postgis',
# 'NAME': config('DB_NAME'),
# 'USER': config('DB_USER'),
# 'PASSWORD': config('DB_PASSWORD'),
# 'HOST': config('DB_HOST'),
# 'PORT': config('DB_PORT'),
# }
#}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
# STATIC_URL = 'static/'
# STATIC_ROOT = os.path.join(BASE_DIR)
# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# MEDIA_URL = '/media/'
# MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
USE_S3 = config('USE_S3') == 'TRUE'
if USE_S3:
# aws settings
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_DEFAULT_ACL = 'public-read'
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
# s3 static settings
AWS_LOCATION = 'static'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# s3 public media settings
PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# 'myKAEKapp.storage_backends.PublicMediaStorage'
else:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# MEDIA_URL = '/mediafiles/'
# MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Heroku: Update database configuration from $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=120)
DATABASES = { 'default': dj_database_url.config() }
DATABASES['default'].update(db_from_env)
DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis'
CSRF_TRUSTED_ORIGINS = ["https://mykaek-gr.herokuapp.com/", "https://mykaek.gr/"]
forms.py
class UploadFileForm(forms.Form):
files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
html
<div class="row justify-content-center align-items-center text-center" style="padding-top: 30px; width: 500px; margin: auto;">
<fieldset name="Multiple Files Upload">
<form method="post" action="/draw-polygons/" enctype="multipart/form-data">{% csrf_token %}
<dl><input class="form-control" type="file" id="formFileMultiple" name="files" required multiple></dl>
<button type="submit" class="btn btn-outline-dark" style="margin-top: 10px;">Φόρτωση</button>
</form>
</fieldset>
</div>
view.py
def upload_multiple_files(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
files_list = request.FILES.getlist('files')
if form.is_valid():
for f in files_list:
try:
'''my code here'''
except:
'''my code here'''
'''my code here'''
return render(request, "multiple/success.html", context)
else:
form = UploadFileForm()
return render(request, 'multiple/multiple.html', {'title': 'myKAEK.gr | Draw Polygons', 'form': form})
def txt_dxf(request):
topos = cache.get('topos')
doc = ezdxf.new("R2000")
msp = doc.modelspace()
doc.layers.add('POLYS_FROM_TXTS')
for i in topos:
msp.add_lwpolyline(i, dxfattribs={"layer": "POLYS_FROM_TXTS"})
out = io.BytesIO()
doc.write(out, fmt='bin')
out.seek(0)
return FileResponse(out, as_attachment=True, filename='polygons_from_txt.dxf')
urls
urlpatterns = [
path('draw-polygons/', views.upload_multiple_files, name='upload_multiple_files'),
path('draw-polygons/export_dxf/', views.txt_dxf, name='txt_dxf'),
]
If I may add something I saw after my original question was posted:
While my custom domain served through cloudflare returns
CSRF Forbidden 403, my herokuapp server returns for the same page
Bad request 400
I don't know if it's relevant but I thought I should add.
Also when I use #csrf_exempt on my view and delete {% csrf_token %} from template I get 400 Bad Request on my custom domain too.
Is it beacouse I use Cloudflare (with cache disabled) between my custom domain and herokuapp?
Please help I really need to get this function work.
Try doing this using Django Forms, it will save you from writing extra code and will handle such edge cases.
https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/#uploading-multiple-files

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.

Not able see the image after uploading on admin panel

I am learning django but i am stuck at Imagefield. I am trying to rename the file and save the image to my media directory where exactly i am going wrong i am not able to understand. It was working fine till worked with filefield. after changing the filefield to imagefield i am getting an page not found.
Not Found: /media/products/926045120/926045120.jpg
above is the error
from django.db import models
import random
import os
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name, ext
def upload_image_path(instance, filename):
# print(instance)
#print(filename)
new_filename = random.randint(1,3910209312)
name, ext = get_filename_ext(filename)
final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext)
return "products/{new_filename}/{final_filename}".format(
new_filename=new_filename,
final_filename=final_filename
)
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
def __str__(self):
return self.title
def __unicode__(self):
return self.title
model.py of product
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__)))
# 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 = 'z45+z23#cgk-fem6x&6i9_n#tz8p3)f^l+f1#8$e^n7(hv&dgz'
# 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',
'products',
]
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 = 'ecommerce.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 = 'ecommerce.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 = 'UTC'
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_my_proj"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root")
products/views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
# Create your views here.
from .models import Product
class ProductListView(ListView):
queryset = Product.objects.all()
template_name = "products/list.html"
# def get_context_data(self, *args, **kwargs):
# context = super(ProductListView, self).get_context_data(*args, **kwargs)
# print(context)
# return context
def product_list_view(request):
queryset = Product.objects.all()
context = {
'object_list': queryset
}
return render(request, "products/list.html", context)
class ProductDetailView(DetailView):
queryset = Product.objects.all()
template_name = "products/detail.html"
def get_context_data(self, *args, **kwargs):
context = super(ProductDetailView, self).get_context_data(*args, **kwargs)
print(context)
#context['abc'] = 123
return context
def product_detail_view(request, pk=None, *args, **kwargs):
#instance = Product.objects.get(pk=pk)
instance = get_object_or_404(Product, pk=pk)
context = {
'object': instance
}
return render(request, "products/detail.html", context)
details.html
{{ object.title }}<br/>
{{ object.description }}<br/>
<img src="{{ object.image.url }}" class="img-fluid"/>
I am able see my images in media directory but it is not able view on page

django1.8, I try to get current logined username. in template got work but in view I got failed [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm quite new in django 1.8.
Now, I'm trying to get current logined username.
I wanna do this. When I post some articles it's author automatically saved to database and displayed in template table.
I already know about
from django.contrib.auth.models import User
and request.user.get_username()
and read lots of articles and QNA about this subject and various tries in two days. But I never find why I only can get username in template but not in view.
I did belows
python manage.py makemigrations BTS(This is name of app)
python manage.py migrate
It works well.
In template, Belows all works well:
{{ user.username }}
{{ request.user.username }}
{{ request.user }}
In views.py I use get_username method like this. No error but it's not work.:
form.username = request.user.get_username()
Every other things works fine. But only above one line get anything only empty null value about username, I guess. I need help.
Here is my code. I skip some unnecessary def.
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.utils import timezone
from django.template import RequestContext, loader
from django.shortcuts import redirect
from .models import BTSinput
from .models import BTSreply
from .forms import BTSinputForm
from .forms import BTSreplyForm
from django.contrib.auth.models import User
def inputvalidate(request):
if request.method == 'POST':
form = BTSinputForm(request.POST or None)
if form.is_valid():
hold = form.save(commit=False)
form.created = timezone.now()
form.updated = timezone.now()
form.username = request.user.get_username()
hold.save()
return redirect('/BTS/list/')
else:
form = BTSinputForm()
return render(request,'BTS/input.html',{'inputform':form})
return render(request,'BTS/input.html',{'inputform':form})
input.html
{% block content %}
{% load widget_tweaks %}
<div class="container">
<div class="starter-template">
<form method="post" action="/BTS/inputvalidate/">
{% csrf_token %}
<div class="form-group">
<p>subject</p>
<p>{{inputform.subject|add_class:"form-control"}}</p>
<p>URLS</p>
<p>{{inputform.urls|add_class:"form-control"}}</p>
<p>text</p>
<p>{{inputform.text|add_class:"form-control"}}</p>
<button type="submit" class="btn btn-default">Confirm</button>
<button type="button" class="btn btn-default">To List</button>
</div>
</form>
</div>
</div>
{% endblock%}
models.py
class BTSinput(models.Model):
subject = models.CharField(max_length=100)
username = models.CharField(max_length=30, blank = True)
text = models.TextField()
urls = models.URLField(max_length = 100)
created = models.DateTimeField(default = datetime.datetime.now)
updated = models.DateTimeField(default = datetime.datetime.now)
forms.py
from django import forms
from django.forms import ModelForm
from BTS.models import BTSinput
from BTS.models import BTSreply
# Create your models here.
class BTSinputForm(ModelForm):
class Meta:
model = BTSinput
fields = ['subject','text','urls']
class BTSreplyForm(ModelForm):
class Meta:
model = BTSreply
fields = ['reply']
I checked my setting.py over and over. But... ^^;;;
Here is my setting.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.8.4.
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 = 'n^63(%(va-3wb9l!!2-vg003f)s(3g=%w1*%tv2(8%l)65g&a2'
# 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',
'QNA',
'BTS',
'accounts',
'widget_tweaks',
)
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 = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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/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 = 'ko-kr'
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/'
Once you have called save with commit=False, you should update the instance, not the form.
if form.is_valid():
hold = form.save(commit=False)
hold.created = timezone.now()
hold.updated = timezone.now()
hold.username = request.user.get_username() # or request.user.username
hold.save()

Using image in a template 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}}