Django Uploading Images
django-admin startproject upload
cd upload
python manage.py startapp uploadimg
settings.py
----------
import os
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'uploadimg'
]
MEDIA_URL='/media/'
# path where media is stored
MEDIA_ROOT=os.path.join(BASE_DIR,'media/')
forms.py
---------
from django import forms
from uploadimg.models import Image
class ImageForm(forms.ModelForm):
"""Form for the image model"""
class Meta:
model = Image
fields = ('title', 'image')
models.py
---------
from django.db import models
class Image(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(upload_to='images')
def __str__(self):
return self.title
class Meta:
db_table = "images"
views.py
--------
from django.shortcuts import render
from uploadimg.forms import ImageForm
def index(request):
if request.method=='POST':
form = ImageForm(request.POST,request.FILES)
if form.is_valid():
form.save()
img_obj=form.instance
return render(request,'index.html',{'form':form,'img_obj':img_obj})
else:
form=ImageForm()
return render(request,'index.html',{'form':form})
urls.py
-------
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from . import views
urlpatterns = [
path('',views.index)
]
if settings.DEBUG:
urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
for project
----------
urls.py
-------
"""upload URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('uploadimg.urls'))
]
index.html
----------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>upload image</title>
</head>
<body>
<h1>Django Uploading Images</h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}{{ form.as_p}}
<button type="submit">Upload</button>
</form>
{% if img_obj %}
<h3>Succesfully uploaded :{{img_obj.title}}</h3>
<img src="{{img_obj.image.url}}" alt="connect" style="max-height:300px"> {% endif %}
</body>
</html>
Comments
Post a Comment