Skip to main content

Create a File Sharing Website in Django

Django is a popular web framework of Python for Web developers. It is used for Backend work. We can create a large project using the Django framework. Most companies like Instagram, Spotify, Mozilla, Pinterest, Disqus, etc are using Django for their Backend. It helps to create a Complex website.






In this post, I will create a File Share Website using the Django framework.

Let's Go.

Our Project structure:-


Follow these steps to create & configure our project:-

Step 1 - Create a project using this command ( django-admin startproject filesharing )

Step 2 - Go inside to our project and create an app in this project ( python manage.py startapp main )

Step 3 - Open project's settings.py file and add the main app in INSTALLED_APPS section.

Step 4 - Create an urls.py file in our main app and add it to project's urls.py file , like this


from django.contrib import admin
from django.urls import path, include


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('main.urls'))
]

Step 5 - Create a Template folder in project. Add it in settings.py file of project.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR/'templates'], # add here
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Step 6 - Create a User and File_Upload models in models.py file

from django.db import models

# Create your models here.
class User(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()
    pwd = models.CharField(max_length=100)
    gender = models.CharField(max_length=20)

    def __str__(self):
        return self.name


class File_Upload(models.Model):
    user = models.ForeignKey(User, models.CASCADE)
    title = models.CharField(max_length=50)
    description = models.TextField()
    file_field = models.FileField(upload_to="")

    def __str__(self):
        return self.title

Step 7 - Register these models in admin.py file


from django.contrib import admin
from .models import User, File_Upload

# Register your models here.
admin.site.register(User)
admin.site.register(File_Upload)

Step 8 - Now let's create our super user using this command ( python manage.py createsuperuser ). It will ask you Username, Email, Password.

Step 9 - Code in views.py file


from django.shortcuts import render, redirect
from .models import User, File_Upload
from django.contrib import messages

# Create your views here.
def index(request):
    if 'user' in request.session:
        all_files = File_Upload.objects.all()
        data = {'files': all_files}
        return render(request, 'index.html', data)
    else:
        return redirect('login')

def login(request):
    if 'user' not in request.session:
        if request.method == 'POST':
            email = request.POST['email']
            pwd = request.POST['pwd']
            userExists = User.objects.filter(email=email, pwd=pwd)
            if userExists.exists():
                request.session["user"] = email
                return redirect('index')
            else:
                messages.warning(request, "Wrong user or details.")
        return render(request, 'login.html')
    else:
        return redirect('index')


def logout(request):
    del request.session['user']
    return redirect('login')


def signup(request):
    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        pwd = request.POST['pwd']
        gender = request.POST['gender']
        if not User.objects.filter(email=email).exists():
            create_user = User.objects.create(name=name, email=email, pwd=pwd,
                            gender=gender)
            create_user.save()
            messages.success(request, "Your account is created successfully!")
            return redirect('login')
        else:
            messages.warning(request, "Email is already registered!")
       
    return render(request, 'signup.html')


def settings(request):
    if 'user' in request.session:
        user_obj = User.objects.get(email = request.session['user'])
        user_files = File_Upload.objects.filter(user = user_obj)

        img_list = []
        audio_list = []
        videos_list = []
        pdfs_list = []

        for file in user_files:
            if str(file.file_field)[-3:] == 'mp3':
                audio_list.append(file)
            elif str(file.file_field)[-3:] == 'mp4' or
                    str(file.file_field)[-3:] == 'mkv':
                videos_list.append(file)
            elif str(file.file_field)[-3:] == 'jpg' or
                    str(file.file_field)[-3:] == 'png' or
                    str(file.file_field)[-3:] == 'jpeg':
                img_list.append(file)
            elif str(file.file_field)[-3:] == 'pdf':
                pdfs_list.append(file)  

        data = {'user_files': user_files, 'videos': len(videos_list),
                'audios': len(audio_list), 'images': len(img_list),
                'pdf': len(pdfs_list), 'img_list': img_list,
                'audio_list': audio_list, 'videos_list': videos_list,
                'pdfs_list': pdfs_list}
        return render(request, 'settings.html', data)

def file_upload(request):
    if request.method == 'POST':
        title_name = request.POST['title']
        description_name = request.POST['description']
        file_name = request.FILES['file_to_upload']

        user_obj = User.objects.get(email=request.session['user'])
        new_file = File_Upload.objects.create(user = user_obj, title=title_name,
                    description=description_name, file_field = file_name)
        messages.success(request, "File is uploaded successfully!")
        new_file.save()
    return render(request, 'file_upload.html')

def delete_file(request, id):
    if 'user' in request.session:
        file_obj = File_Upload.objects.get(id = id)
        file_obj.delete()
        return redirect('settings')
    else:
        return redirect('login')

Step 10 - Create some path in urls.py file in main app.


from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name="index"),
    path('login/', views.login, name="login"),
    path('logout/', views.logout, name="logout"),
    path('signup/', views.signup, name="signup"),
    path('settings/', views.settings, name="settings"),
    path("file_upload/", views.file_upload, name="file_upload"),
    path('delete/<str:id>/', views.delete_file, name="delete_file")
]

Step 11 - Add some html files in Template folder

File 1-  base.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{% block title %}{% endblock %}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/
     bootstrap.min.css" rel="stylesheet"
   integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
     crossorigin="anonymous">
    <style>
      ::selection
      {
        background-color: rgb(5, 220, 5);
        color: white;
      }
    </style>
  </head>
  <body class="bg-primary text-light">

    <nav class="navbar navbar-expand-lg bg-body-tertiary bg-primary"
    data-bs-theme="dark">
        <div class="container-fluid">
          <a class="navbar-brand" href="{% url 'index' %}">File Sharing</a>
          <button class="navbar-toggler" type="button" data-bs-toggle="collapse"
        data-bs-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false"
        aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
              <li class="nav-item">
                <a class="nav-link" aria-current="page"
                href="{% url 'index' %}">Home</a>
              </li>
              {% if not request.session.user %}
                <li class="nav-item">
                  <a class="nav-link" href="{% url 'login' %}">Login</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="{% url 'signup' %}">Signup</a>
                </li>
              {% else %}
                <li class="nav-item">
                  <a class="nav-link" href="{% url 'file_upload' %}">Upload a file</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="{% url 'settings' %}">Settings</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="{% url 'logout' %}">Logout</a>
                </li>
              {% endif %}
            </ul>
            <form class="d-flex" role="search">
              <input class="form-control me-3" type="search" placeholder="Search"
                aria-label="Search">
              <button class="btn btn-outline-success" type="submit">Search</button>
            </form>
          </div>
        </div>
      </nav>
     
    {% block body %}
    {% endblock %}
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/
    bootstrap.bundle.min.js"
    integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN"
    crossorigin="anonymous"></script>
  </body>
</html>


File 2 - index.html

{% extends 'base.html' %}

{% block title %}
    Home
{% endblock %}

{% block body %}
    {% for file in files reversed %}
        <div class="container border border-success my-5 py-4  form-control">
            <h1 class="mx-5">
                {{file.title}}
            </h1>
            <small><p class="mx-5 text-primary">uploaded by
            <i>{{file.user.name}}</i></p></small>
            <p class="mx-5">
                {{file.description}}
            </p>
            <div class="mx-5">
                <a class="btn btn-outline-success btn-sm"
                href="media/{{file.file_field}}/" target="_blank">View</a>
                <a class="btn btn-outline-success btn-sm"
                href="media/{{file.file_field}}/" download>Download</a>
            </div>
        </div>
    {% endfor %}
{% endblock %}


File 3 - login.html

{% extends 'base.html' %}

{% block title %}

    Login

{% endblock %}

{% block body %}
   
    <div class="container w-25 my-5">
        <h2 class="my-5">Login</h2>
        <hr>
        {% if messages %}
            {% for message in messages %}
                <div class="alert alert-{{message.tags}} alert-dismissible fade show"
             role="alert">
                    {{message}}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"
             aria-label="Close"></button>
                </div>
            {% endfor %}
        {% endif %}
        <form action="{% url 'login' %}" method="post">
            {% csrf_token %}
            <div class="mb-3">
                <input type="email" class="form-control" name="email"
             id="exampleFormControlInput1" placeholder="Email" required>
            </div>
            <div class="mb-3">
                <input type="password" class="form-control" name="pwd"
             id="exampleFormControlInput1" placeholder="Password" required>
            </div>
            <div class="mb-3">
                <input type="submit" class="btn btn-danger w-100" value="Login">
            </div>
            <center>
                Don't have an account? <a href="{% url 'signup' %}"
            class="text-light">Signup</a>
            </center>
        </form>
    </div>

{% endblock %}


File 4 - signup.html

{% extends 'base.html' %}

{% block title %}

    Create an Account

{% endblock %}

{% block body %}
    <div class="container w-25 my-5">
        <h2 class="my-5">Create your account</h2>
        <hr>
        {% if messages %}
            {% for message in messages %}
            <div class="alert alert-{{message.tags}} alert-dismissible fade show"
            role="alert">
                {{message}}
                <button type="button" class="btn-close" data-bs-dismiss="alert"
            aria-label="Close"></button>
            </div>
            {% endfor %}
        {% endif %}
        <form action="{% url 'signup' %}" method="post">
            {% csrf_token %}
            <div class="mb-3">
                <input type="text" class="form-control" name="name"
            id="exampleFormControlInput1" placeholder="Name" required>
            </div>
            <div class="mb-3">
                <input type="email" class="form-control" name="email"
            id="exampleFormControlInput1" placeholder="Email" required>
            </div>
            <div class="mb-3">
                <input type="password" class="form-control" name="pwd"
            id="exampleFormControlInput1" placeholder="Password" required>
            </div>
            <div class="mb-3">
                <select class="form-select" name="gender"
            aria-label="Default select example" required>
                    <option value="1">Male</option>
                    <option value="2">Female</option>
                </select>
            </div>
           
            <div class="mb-3">
                <input type="submit" class="btn btn-danger w-100" value="Signup">
            </div>
        </form>
        <center>
            Already have an account? <a href="{% url 'login' %}"
        class="text-light">Login</a>
        </center>
    </div>
{% endblock %}

File 5 - settings.html

{% extends 'base.html' %}

{% block title %}
    Settings
{% endblock %}

{% block body %}

    <div class="container form-control my-4">
        <h3>Welcome! {{request.session.user}}</h3>
    </div>

    <div class="container">
        <table class="table">
            <tbody>
                <tr>
                    <td>
                        <div class="card w-50 py-3 px-4">
                            <h4 class="card-text">Videos: {{videos}}</h4>
                        </div>
                    </td>

                    <td>
                        <div class="card w-50 py-3 px-4">
                            <h4 class="card-text">Audios: {{audios}}</h4>
                        </div>
                    </td>

                    <td>
                        <div class="card w-50 py-3 px-4">
                            <h4 class="card-text">Images: {{images}}</h4>
                        </div>
                    </td>

                    <td>
                        <div class="card w-50 py-3 px-4">
                            <h4 class="card-text">Pdfs: {{pdf}}</h4>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
<div class="container form-control">
    <nav>
        <div class="nav nav-tabs" id="nav-tab" role="tablist">
            <button class="nav-link" id="nav-images-tab" data-bs-toggle="tab"
data-bs-target="#nav-images" type="button" role="tab" aria-controls="nav-images"
aria-selected="true">Images</button>
            <button class="nav-link" id="nav-audios-tab" data-bs-toggle="tab"
data-bs-target="#nav-audios" type="button" role="tab" aria-controls="nav-audios"
aria-selected="false">Audios</button>
            <button class="nav-link" id="nav-videos-tab" data-bs-toggle="tab"
data-bs-target="#nav-videos" type="button" role="tab" aria-controls="nav-videos"
aria-selected="false">Videos</button>
            <button class="nav-link" id="nav-pdfs-tab" data-bs-toggle="tab"
data-bs-target="#nav-pdfs" type="button" role="tab" aria-controls="nav-pdfs"
aria-selected="false">Pdfs</button>
        </div>
        <div class="tab-content" id="nav-tabContent">
            <div class="tab-pane fade show active" id="nav-images" role="tabpanel"
aria-labelledby="nav-images-tab" tabindex="0">
                {% if img_list %}
                    {% for img in img_list%}
                        <div class="container my-3">
                            <h3>{{img.title}}</h3>
                            <p>{{img.description}}</p>
                            <a class="btn btn-outline-success btn-sm"
href="../media/{{img.file_field}}/" target="_blank">View</a>
                            <a class="btn btn-outline-success btn-sm"
href="../media/{{img.file_field}}/" download>Download</a>
                            <a href="{% url 'delete_file' img.id %}"
class="btn btn-outline-danger btn-sm">Delete</a>
                        </div>
                        <hr>
                    {% endfor %}
                {% else %}
                    No images
                {% endif %}
            </div>
            <div class="tab-pane fade" id="nav-audios" role="tabpanel"
aria-labelledby="nav-audios-tab" tabindex="0">
                {% if audio_list %}
                    {% for aud in audio_list %}
                        <div class="container my-3">
                            <h3>{{aud.title}}</h3>
                            <p>{{aud.description}}</p>
                            <a class="btn btn-outline-success btn-sm"
href="../media/{{aud.file_field}}/" target="_blank">View</a>
                            <a class="btn btn-outline-success btn-sm"
href="../media/{{aud.file_field}}/" download>Download</a>
                            <a href="{% url 'delete_file' aud.id %}"
class="btn btn-outline-danger btn-sm">Delete</a>
                        </div>
                        <hr>
                    {% endfor %}
                {% else %}
                    No audios
                {% endif %}
            </div>
            <div class="tab-pane fade" id="nav-videos" role="tabpanel"
aria-labelledby="nav-videos-tab" tabindex="0">
                {% if videos_list %}
                    {% for vid in videos_list %}
                        <div class="container my-3">
                            <h3>{{vid.title}}</h3>
                            <p>{{vid.description}}</p>
                            <a class="btn btn-outline-success btn-sm"
href="../media/{{vid.file_field}}/" target="_blank">View</a>
                            <a class="btn btn-outline-success btn-sm"
href="../media/{{vid.file_field}}/" download>Download</a>
                            <a href="{% url 'delete_file' vid.id %}"
class="btn btn-outline-danger btn-sm">Delete</a>
                        </div>
                        <hr>
                    {% endfor %}
                {% else %}
                    No videos
                {% endif %}
            </div>
            <div class="tab-pane fade" id="nav-pdfs" role="tabpanel"
aria-labelledby="nav-pdfs-tab" tabindex="0">
                {% if pdfs_list %}
                    {% for pdf in pdfs_list %}
                        <div class="container my-3">
                            <h3>{{pdf.title}}</h3>
                            <p>{{pdf.description}}</p>
                            <a class="btn btn-outline-success btn-sm"
href="../media/{{pdf.file_field}}/" target="_blank">View</a>
                            <a class="btn btn-outline-success btn-sm"
href="../media/{{pdf.file_field}}/" download>Download</a>
                            <a href="{% url 'delete_file' pdf.id %}"
class="btn btn-outline-danger btn-sm">Delete</a>
                        </div>
                        <hr>
                    {% endfor %}
                {% else %}
                    No pdfs
                {% endif %}
            </div>
        </div>
    </nav>
</div>    
   
{% endblock %}


File 6 - file_upload.html

{% extends 'base.html' %}

{% block title %}

    File Upload

{% endblock %}

{% block body %}

    <div class="container w-50">
        <h2 class="my-3">Upload a File</h2>
        <hr>
        <form class="form-control" action="{% url 'file_upload' %}" method="post"
enctype="multipart/form-data">
            {% csrf_token %}
           
            {% if messages %}
                {% for message in messages %}
                    <div class="alert alert-{{message.tags}} alert-dismissible fade
show" role="alert">
                        {{message}}
                        <button type="button" class="btn-close"
data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                {% endfor %}
            {% endif %}
           
            <input type="text" name="title" placeholder="Title"
class="form-control my-3">
            <textarea placeholder="Description" name="description"
class="form-control my-3"></textarea>
            <input type="file" class="form-control my-3" name="file_to_upload">
            <input type="submit" value="Upload" class="btn btn-outline-primary my-3">
        </form>
    </div>

{% endblock %}

Step 12 - For successful file uploadation we have to add some important lines in settings.py & urls.py.


# In setting.py file

STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR/'static']

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR/'static'/'media'



# In urls.py file

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('main.urls'))
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


Our project is created succesfully. Now lets start our server using this command - 

python manage.py runserver


Thanks for reading my blog. You can read my others post too. I hope you get some knowledgeable stuff.

Comments

Popular posts from this blog

Top 3 YouTube Videos Downloader

Top YouTube Video Downloader YouTube is the largest website within the world. It is owned by Google. There are 1.3 billion peoples who use Youtube. Almost 5 Billion videos are watched every day all over the world. 30 Million viewers get information from YouTube per day. But there's a drag that we will not download YouTube video on Desktop/Computer.  So during this post i'm talking about top YouTube video downloader. Savefrom.net Y2Mate Freemake Savefrom.net This Website is fastest YouTube video downloader. On this site, you'll download videos in diffrent types of video format like MP4, MP3, WEBM, 3GP, 480p,360p etc. How to download videos on Savfrom.net  There is a green Download button. Click on it and select you desired video format and save it on your desired folder. Savefrom.net gives you extension for Chrome, Firefox and Opera which will help you for easy life.          Y2Mate.guru Y2mate is my second option for video download. If savefrom.net is not workin

[Top 5] Superhero Hindi Youtube channel( 5 बेहतरीन सुपरहीरो हिंदी यूट्यूब चैनल)

Do any of you watch the comics / movies of superheros or any news related to them? If yes, then I will tell you about the 5 best superhero Hindi YouTube channels which give a news related to superheros. Avengers: End Game is the highest grossing Hollywood movie and is a superheroes movie. You must have guessed that superheroes are liked all over the world. There are some platforms that give every news related to them. One of these is YouTube, where people tell every news visually. So today we will talk on this topic 1.) Super Super     This is a channel that has made a lot of fans in a very short time. This channel gives updates about superheroes from both Marvel and DC universe. The special thing about this channel is the introduction of the channel- Intro. Along with this, youtuber also cracks jokes in between videos so that viewers like it.         JOINED           --                  2 JAN 2017       OWNER         --                  Aman Sinha       SUBSCRIB

How to use Indian Micro Blogging Site 'Koo'?

How to use Indian Micro Blogging Site 'Koo' In the previous, Blog post I have discussed about Indian Micro Blogging Site 'Koo' where I discuss about Self-Reliant App Challenge in India and Koo is the winner of this challenge. But now I am discussing how to use 'Koo' app in this post. Koo is micro blogging site and it is alternative of Twitter. We cover very important points in this post:-- What is Koo? Who is the creator of Koo? Why the Koo app was created? How to use Koo app? See Also:-- Indian Programmers created Twitter's alternative named KOO  What is KOO? KOO is a micro blogging site like Twitter. It is available in 4 languages Hindi, Kannada, Tamil and Telugu. And some of the indian languages will be include soon.  Creators choose KOO as name of this app because KOO is the voice of Loyal bird which is very sweet. Who is the creator of KOO? Koo app has been created by Aprameya Radhakrishna and Mayank Bidawatka back in March. They are winner