S
S
ScroogeM2016-11-05 22:55:52
Django
ScroogeM, 2016-11-05 22:55:52

How to upload images to the site. Django?

I'm trying to display an image on the page, but nothing happens. I was looking for similar topics and all the solutions proposed there did not fit. I need your help. Thanks in advance.
model:

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/'`

View:
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)

Template:
{% 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 %}

and urls:
urlpatterns = [
    url(r'^$',  news, name="main"),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Shevchenko, 2016-11-06
@ScroogeM

ForeignKey is a many-to-one relationship. You can create many images by placing postthe same news in the field.
Therefore post.image, this is not the image itself, but a manager that returns all images for this news. In other words, post.imageit will return the same as Images.objects.filter(post=post). There are several ways to fix this.
If you want everything to just work without major changes:
If the news really can have a lot of images

{% for image in new.image.all %}
     <img src="{{ image.image.url }}">
{% endfor %}

If a news item can only have one image:
class Images(models.Model):
    post = models.OneToOneField(News, default=None, related_name="image")
    image = models.ImageField(upload_to=settings.MEDIA_ROOT,
                              verbose_name="Image")

OneToOneField is a one-to-one relationship. In this case post.image, it will immediately return the image.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question