python - serve - mostrar imagenes django
cómo subir imágenes en un servidor web. django (2)
Quiero mostrar imágenes en mi sitio web y no puedo encontrar mi error. En otras publicaciones vi la necesidad de actualizar settings.py
, pero configuré MEDIA_ROOT y MEDIA_URL como en el ejemplo, pero no me sirve.
modelos:
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="Теги")
#user = models.ForeignKey(User)
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")
ajustes
MEDIA_ROOT = os.path.join(BASE_DIR, ''media'')
MEDIA_URL = ''/media/''`
ver
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():
post_form = form.save(commit=False)
#post_form.user = request.user
post_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
images = Images.objects
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, ''news'': images}, context)
y plantilla
{% 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 %}
¿Dónde está mi error?
Esta línea :
images = Images.objects
Cámbielo a images = Images.objects.all () y verifique si funciona?
{% for new in news %}
<h2>{{ new.title }}</h2>
{% for image in new.image.all %}
<img src="{{image.image.url }}">
{% endfor %}
Porque post = models.ForeignKey (News, default = None, related_name = "image") tiene muchas imágenes.