Hello Friends, I am Madhuban Khatri - A Self Taught Python Developer. I was working on another new project that is File Share Website. It is an updated version of previos projectd.
You can add more functionality to my project to improve working process. Now I am sharing my source code of File Share Website.
First , We have to create a Django project and an App in this project.
# To create a project
django-admin startproject <your_project_name>
# To create an App
python manage.py startapp <your_app_name>
Code Files are below:-
Views.py
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')
Urls.py (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")
]
Urls.py(Project)
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)
Models.py
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
Admin.py
from django.contrib import admin
from .models import User, File_Upload
# Register your models here.
admin.site.register(User)
admin.site.register(File_Upload)
Settings.py
# Add some lines of Code in Settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR/'static']
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR/'static'/'media'
Templates Folder contains Html Files
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>
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 %}
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 %}
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 %}
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_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 %}
Thank for reading file blog.
You can check my other posts to get knowledgeable stuff. These projects are useful for College students or others who want to get idea for their projects.
Top comments (2)
bro i add search bar successfully
bro search bar code is miss in this project