B
B
bwylla2019-02-25 19:40:29
Django
bwylla, 2019-02-25 19:40:29

How can I display an image on a website page?

I have a form that accepts images, they are stored in the media folder, but I don't know how to display these images on the page. It is desirable that it shows exactly the last loaded image.
Thank you in advance!!!
# index.html
{% load static %}

{% block content %}
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form }}
        <input type="submit">
    </form>
{% endblock content %}

#photo.html
{% extends 'blog/index.html' %}
{% block content %}
hello
{% endblock content %}

#models.py
class UploadFile(models.Model):
    title = models.CharField(max_length=50)
    image = models.ImageField(upload_to='media')

#views.py
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('photo')
    else:
        form = UploadFileForm()
    return render(request, 'blog/index.html', {'form': form})

#urls.py applications
urlpatterns = [
    path('', upload_file),
    path('photo/', post_list, name='photo')
]

#urls.py root
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls'))
] + 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)
S
Sergey Gornostaev, 2019-02-25
@bwylla

views.py

def post_list(request):
    return render(request, 'photo.html', {'last_photo': UploadFile.objects.last()})

photo.html I highly recommend reading the Django manual to avoid such primitive questions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question