How to render image in my Django Blog Template? -
hi guys have blog setup , want add ability image or thumbnail included in every blog post. i'm having trouble getting location of file , blog template match , show image. i'm having difficulties integrating imagewiththumbnail model entry model.
post.html
{% include 'head.html' %} {% include 'navbar.html' %} {% load staticfiles %} {% load django_markdown %} <div class="container"> <div class="post"> <h2><a href="{% url "entry_detail" slug=object.slug %}">{{ object.title }}</a></h2> <p class="meta"> {{ object.created }} | tagged under {{ object.tags.all|join:", " }} <p> created {{ 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 vizualytic project. generated 'django-admin startproject' using django 1.8.3. more information on file, see https://docs.djangoproject.com/en/1.8/topics/settings/ full list of settings , values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # build paths inside project 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 production # see https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # security warning: keep secret key used in production secret! secret_key = '#ic_*)dw$fxp+p_c=3e=91ujzivxurqf7y7572z9&sfs19aek%' # security warning: don't run 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 . 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 django.core.urlresolvers import reverse 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 method came # http://snipt.net/danfreak/generate-thumbnails-in-django-with-pil/ # if there no image associated this. # not create thumbnail if not self.image: return pil import image cstringio import stringio django.core.files.uploadedfile import simpleuploadedfile import os # set our max thumbnail size in 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 want thumbnail using pil's image image = image.open(stringio(self.image.read())) # convert rgb if necessary # limodou on djangosnippets.org # http://www.djangosnippets.org/snippets/20/ # # commented part since messes png files # #if image.mode not in ('l', 'rgb'): # image = image.convert('rgb') # use our pil image object create thumbnail, # has thumbnail() convenience method contrains proportions. # additionally, use image.antialias make image better. # without antialiasing image pattern artifacts may result. image.thumbnail(thumbnail_size, image.antialias) # save thumbnail temp_handle = stringio() image.save(temp_handle, pil_type) temp_handle.seek(0) # save image simpleuploadedfile can saved # imagefield suf = simpleuploadedfile(os.path.split(self.image.name)[-1], temp_handle.read(), content_type=django_type) # save simpleuploadedfile image field self.thumbnail.save('%s_thumbnail.%s'%(os.path.splitext(suf.name)[0],file_extension), suf, save=false) def save(self): # create thumbnail self.create_thumbnail() super(imagewiththumbnail, self).save()
any appreciated.
thanks
you need:
<img src="{{ object.thumbnail.url }}" alt="my image"/>
note {% static 'file.extension' %}
used render static files.
Comments
Post a Comment