P
P
P0f1g1st1122017-08-30 22:54:40
Django
P0f1g1st112, 2017-08-30 22:54:40

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>

result is zero.
code in models.py
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

further code in views.py
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,
                      })

and if it is useful, then the code in the urls.py of the project itself
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}),
]

settings.py _
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/'

django version 1.11.4; static, media folders are created. Well, there are no problems with static, but media does not want to work in any way.
Thanks for the help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
P0f1g1st112, 2017-08-31
@P0f1g1st112

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 version
url(r'^$', include("mainpage.urls")),

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question