article

Sunday, April 12, 2020

Django File Upload and save data to database sqlite3


Django File Upload and save data to database sqlite3

Django provides built-in library and methods that help to upload a file to the server.

The forms.FileField() method is used to create a file input and submit the file to the server. While working with files, make sure the HTML form tag contains enctype="multipart/form-data" property.
 
#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" 
 
#forms.py
from django import forms  
from myapp.models import StudentForm  #models.py
   
class StudentForm(forms.ModelForm):  
    class Meta:  
        model = StudentForm  
        fields = "__all__" 
 
#view.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})  
//templates/index.html
<html>
<head>
<title>Django File Upload</title>
</head>
<body>
<p><h1>Django File Upload</h1></p>
<form method="POST" class="post-form" enctype="multipart/form-data">  
        {% csrf_token %}  
        {{ form.as_p }}  
        <button type="submit" class="save btn btn-default">Save</button>  
</form>  
</body>  
</html>
 
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  
urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('index/', views.index),  
] 
 
#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)  

Related Post