article

Thursday, April 28, 2022

Django File Upload Save to Mysql Database

Django File Upload Save to Mysql Database

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Mysql tabase table
CREATE TABLE `student` (
  `id` bigint(20) NOT NULL,
  `firstname` varchar(50) NOT NULL,
  `lastname` varchar(50) NOT NULL,
  `email` varchar(254) NOT NULL,
  `file` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Register App myapp and
Connect to MySQL Database
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
 
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Model
myapp/models.py
//myapp/models.py
from django.db import models

# Create your models here.
class StudentForm(models.Model):  
    firstname = models.CharField("Enter first name", max_length=50)  
    lastname  = models.CharField("Enter last name", max_length = 50)  
    email     = models.EmailField("Enter Email")  
    file      = models.FileField() # for creating file input  
  
    class Meta:  
        db_table = "student"
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\my_project_django\testdev>python manage.py makemigrations
C:\my_project_django\testdev>python manage.py migrate
Creating View
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render
from django.http import HttpResponse  
from myapp.functions import handle_uploaded_file  #functions.py
from myapp.forms import StudentForm #forms.py
  
def index(request):  
    if request.method == 'POST':  
        student = StudentForm(request.POST, request.FILES)  
        if student.is_valid():  
            handle_uploaded_file(request.FILES['file'])  
            model_instance = student.save(commit=False)
            model_instance.save()
            return HttpResponse("File uploaded successfuly")  
    else:  
        student = StudentForm()  
        return render(request,"index.html",{'form':student}) 
myapp/forms.py
 
////myapp/forms.py
from django import forms  
from myapp.models import StudentForm  #models.py
    
class StudentForm(forms.ModelForm):  
    class Meta:  
        model = StudentForm  
        fields = "__all__"

    def __init__(self, *args, **kwargs):
            super(StudentForm, self).__init__(*args, **kwargs)
            for field_name, field in self.fields.items():
                field.widget.attrs['class'] = 'form-control'	
myapp/functions.py
 
//myapp/functions.py
def handle_uploaded_file(f):  
    with open('myapp/static/upload/'+f.name, 'wb+') as destination:  
        for chunk in f.chunks():  
            destination.write(chunk) 
myapp/urls.py
 
//myapp/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index')
]			
myapp/templates/index.html
//myapp/templates/index.html
<html>
<head>
<title>Django File Upload - cairocoders</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container" style="padding:20px;">
    <div class="row">
        <div class="col-12">
            <p><h1>Django File Upload Save to Mysql Database</h1></p>
            <form method="POST" class="post-form" enctype="multipart/form-data">  
                    {% csrf_token %}  
                    {{ form.as_p }}  
                <button type="submit" class="btn btn-primary">Save</button>  
            </form>  
        </div>
    </div>
</div>
</body>  
</html>
Run : C:\django\devproject>python manage.py runserver

Related Post