Giter Site home page Giter Site logo

alibigdeli / django-multiple-file-upload-sample Goto Github PK

View Code? Open in Web Editor NEW
6.0 1.0 0.0 11.15 MB

a simple application to show you how to upload mutiple files and images in requests

License: MIT License

Dockerfile 0.49% Python 49.49% HTML 50.02%
django drf file restframework upload multiplefileuploading

django-multiple-file-upload-sample's Introduction

Django Multiple File Upload Template

Sample Project to show you how to implement multiple file upload with api and django form

python django docker postgresql git

Guideline

Goal

This project main goal is to provide a sample to show you how to implement multiple file uploading with django form and api.

Development usage

You'll need to have Docker installed. It's available on Windows, macOS and most distros of Linux.

If you're using Windows, it will be expected that you're following along inside of WSL or WSL 2.

That's because we're going to be running shell commands. You can always modify these commands for PowerShell if you want.

Clone the repo

Clone this repo anywhere you want and move into the directory:

git clone https://github.com/AliBigdeli/Django-Multiple-File-Upload-Sample.git

Enviroment Varibales

enviroment varibales are included in docker-compose.yml file for debugging mode and you are free to change commands inside:

services:
  backend:
  command: sh -c "python manage.py check_database && \ 
                      yes | python manage.py makemigrations  && \
                      yes | python manage.py migrate  && \                    
                      python manage.py runserver 0.0.0.0:8000"
    environment:      
      - DEBUG=True

Build everything

The first time you run this it's going to take 5-10 minutes depending on your internet connection speed and computer's hardware specs. That's because it's going to download a few Docker images such as minio and build the Python + requirements dependencies. and dont forget to create a .env file inside dev folder for django and postgres with the samples.

docker compose up --build

Now that everything is built and running we can treat it like any other Django app.

Note

If you receive an error about a port being in use? Chances are it's because something on your machine is already running on port 8000. then you have to change the docker-compose.yml file according to your needs.

Check it out in a browser

Visit http://localhost:8000 in your favorite browser.

Model schema

a simple model for testing purposes

from django.db import models


# Create your models here.

class Photo(models.Model):
    file = models.ImageField(upload_to="gallery/")

Form Base

this is flow of form base uploading

forms.py

from django import forms
from .models import Photo

class PhotoForm(forms.ModelForm):
    file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
    class Meta:
        model = Photo
        fields = ('file', )

views.py

from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views.generic import ListView,FormView,CreateView
from .forms import PhotoForm
from .models import Photo
# Create your views here.


class UploadView(CreateView):
    template_name = 'website/index.html'
    form_class = PhotoForm
    success_url = '/'


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["gallery"] = Photo.objects.all()
        return context
    
    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        files = request.FILES.getlist('file')
        
        if 'file' not in request.FILES or not form.is_valid():
            return HttpResponseRedirect(reverse_lazy("website:index"))
        
        if form.is_valid():
            for file in files:
                Photo.objects.create(file=file)
            return HttpResponseRedirect(self.request.path_info)
        else:
            return self.form_invalid(form)
    
    

API Base

this is flow of api base uploading

serializers.py

from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from ..models import Photo


class PhotoSerializer(serializers.Serializer):
    file = serializers.FileField(max_length=None, allow_empty_file=False)

views.py

from rest_framework.response import Response
from rest_framework import status, viewsets
from rest_framework.parsers import MultiPartParser


from django.views.decorators.csrf import csrf_exempt

from .serializers import *
from ..models import *


class PhotoModelViewSet(viewsets.ModelViewSet):

    serializer_class = PhotoSerializer
    parser_classes = [MultiPartParser]

    @csrf_exempt
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
                
        if 'file' not in request.FILES or not serializer.is_valid():
            return Response({"details":"there is an issue with uploaded files"},status=status.HTTP_400_BAD_REQUEST)
        
        for file in request.FILES.getlist('file'):
            Photo.objects.create(file=file)
        
        return Response({"details":"uploaded successfully"}, status=status.HTTP_201_CREATED)

Test Upload

for testing the upload mechanism you just need to hit on either form base or api base file selection and then choose one or more files which you want to upload. then hit ok and upload it. done!

License

MIT.

Bugs

Feel free to let me know if something needs to be fixed. or even any features seems to be needed in this repo.

django-multiple-file-upload-sample's People

Contributors

alibigdeli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.