Пытаюсь вывести изображение на странице, но ничего не происходит. Искал похожие топики и все предложенные там решения не подошли. Нужна ваша помощь. Заранее спасибо.
модель:
class News(models.Model):
title = models.CharField(max_length=200, unique=True,
verbose_name="Заголовок")
description = models.TextField(verbose_name="Краткое содержание")
posted = models.DateField(default=datetime.date.today(), db_index=True, verbose_name="Опубликвана")
tags = TaggableManager(blank=True, verbose_name="Теги")
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
class Meta:
ordering = ['-posted']
verbose_name = "новость"
verbose_name_plural = "нвости"
def get_image_filename(self, filename):
title = self.News.title
slug = slugify(title)
return "post_images/%s-%s" % (slug, filename)
class Images(models.Model):
post = models.ForeignKey(News, default=None, related_name="image")
image = models.ImageField(upload_to=settings.MEDIA_ROOT,
verbose_name="Image")
settings
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'`
Вьюха:
def news(request):
context = RequestContext(request)
ImageFormSet = modelformset_factory(Images, form=ImageForm,
extra=3)
if request.method == 'POST':
form = NewsForm(request.POST)
formset = ImageFormSet(request.POST, request.FILES,
queryset=Images.objects.none())
if form.is_valid() and formset.is_valid():
form.save()
for forma in formset.cleaned_data:
try:
image = forma['image']
photo = Images(post=post_form, image=image)
photo.save()
messages.add_message(request, messages.SUCCESS,
"!!!")
except KeyError:
pass
return redirect("main")
else:
print(form.errors, formset.errors)
else:
form = NewsForm()
formset = ImageFormSet(queryset=Images.objects.none())
try:
page_num = request.GET.get('page')
except KeyError:
page_num = 1
all_news = News.objects.all()
paginator = Paginator(all_news, 10)
try:
pages = paginator.page(page_num)
except InvalidPage:
pages = paginator.page(1)
return render_to_response("mainpage.html", {'form': form, 'formset': formset,
'pages': pages,}, context)
Темплейт:
{% block content %}
{% for new in pages %}
<h2>{{ new.title }}</h2>
<img src="{{ new.image.url}}">
{% endfor %}
<form action="" method="post" enctype="multipart/form-data">
{% include "generic/form.html" %}
<input type="submit" value="создать">
</form>
{% endblock %}
и урлы:
urlpatterns = [
url(r'^$', news, name="main"),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)