In this tutorial, I will show you how to allow users to download images from your website.
blogs/models.py
from django.db import models
class Project(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField()
blogs/views.py
from django.shortcuts import render
from .models import Project
def index(request):
projects = Project.objects.all()
return render(request, 'blogs/index.html',{'projects':projects})
blogs/urls.py
from . import views
from django.urls import path
app_name = 'blogs'
urlpatterns = [
path('', views.index, name='index'),
]
blogs/admin.py
from django.contrib import admin
from .models import Project
admin.site.register(Project)
blogs/templates/blogs/index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1> This is my blog </h1>
{% for project in projects %}
<h2>{{project.name}}</h2>
<a href="{{project.image.url}}" download> {{project.name}}</a>
{% endfor %}
</body>
</html>
mysite/settings.py
.
.
.
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blogs',
]
.
.
.
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
.
.
.
mysite/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("blogs.urls")),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
0 comment