Answer the question
In order to leave comments, you need to log in
Django loading images from model to template?
Hello! I read a lot of similar questions and in general, nothing helped.
Task: display images from the model to the template. main.html
code
<a href="#"><img class="img-responsive" src="{{ article_newest.image.url }}" alt=""></a>
class Article(models.Model):
class Meta:
db_table = "Статья"
verbose_name_plural = "Статьи"
ordering = ['-date_create']
title = models.CharField(max_length=250, verbose_name='Заголовок')
date_create = models.DateTimeField(u'Дата публикации', auto_now=True)
content = models.TextField(max_length=10000)
views = models.IntegerField(default=0)
image = models.ImageField(null=True, blank=True)
def __unicode__(self):
return self.title
from django.shortcuts import render_to_response
from .models import Article
def mainpage(request):
article_newest = Article.objects.order_by('-date_create')[0]
articles = Article.objects.order_by('-date_create')[1:5]
return render_to_response('main.html', {
'article_newest': article_newest,
'articles': articles,
})
from django.conf.urls import url, include
from django.contrib import admin
from django.views.static import serve
from . import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include("mainpage.urls")),
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
#STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
Answer the question
In order to leave comments, you need to log in
After reading dozens of answers to this question, I finally found the answer. Maybe someone will come in handy. The only problem was that in urls.py it was necessary to write the $ sign at the end of the regular expression.
and here is a working versionurl(r'^$', include("mainpage.urls")),
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question