Pretty nice commit overall, made the upload mechanic much more realistic and usable. Only thing left for the upload is the user id assignment. Check new ideas in discord.

This commit is contained in:
Yamozha 2021-02-17 03:00:51 +02:00
parent e5db5a969f
commit 322047b51b
43 changed files with 161 additions and 28 deletions

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

View File

@ -11,9 +11,9 @@
<button type="submit">Upload</button> <button type="submit">Upload</button>
</form> </form>
{% if file_url %} {% if img_obj %}
<h3>Succesfully uploaded</h3> <h3>Succesfully uploaded : {{img_obj.title}}</h3>
<img src="{{ file_url }}" alt="connect" style="max-height:300px"> <img src="{{ img_obj.image.url}}" alt="connect" style="max-height:300px">
{% endif %} {% endif %}
{% else %} {% else %}
<p>You are not logged in</p> <p>You are not logged in</p>

View File

@ -0,0 +1,22 @@
{% extends 'base.html' %}
{% block title %} Home {% endblock %}
{% block content %}
{% if user.is_authenticated %}
Hi {{ user.username }}!<br>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
{% if img_obj %}
<h3>Succesfully uploaded : {{img_obj.title}}</h3>
<source src="{{ img_obj.image.url}}" type="video/mp4" alt="connect" style="max-height:300px">
{% endif %}
{% else %}
<p>You are not logged in</p>
<a href="{% url 'login' %}">Log In</a>
{% endif %}
{% endblock %}

Binary file not shown.

View File

@ -1,9 +1,15 @@
from django import forms from django import forms
from .models import Image from .models import Image, Videos
class ImageForm(forms.ModelForm): class ImageForm(forms.ModelForm):
"""Form for the image model""" """Form for the image model"""
class Meta: class Meta:
model = Image model = Image
fields = ('image',) fields = ('title', 'image')
class VideoForm(forms.ModelForm):
"""Form for the image model"""
class Meta:
model = Videos
fields = ('title', 'video')

View File

@ -0,0 +1,25 @@
# Generated by Django 3.1.6 on 2021-02-16 22:41
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('upload', '0003_auto_20210209_1806'),
]
operations = [
migrations.AddField(
model_name='image',
name='title',
field=models.CharField(default=django.utils.timezone.now, max_length=200),
preserve_default=False,
),
migrations.AlterField(
model_name='image',
name='image',
field=models.ImageField(upload_to='images'),
),
]

View File

@ -0,0 +1,25 @@
# Generated by Django 3.1.6 on 2021-02-16 22:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('upload', '0004_auto_20210217_0041'),
]
operations = [
migrations.CreateModel(
name='Videos',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('video', models.FileField(upload_to='videos/')),
],
options={
'verbose_name': 'video',
'verbose_name_plural': 'videos',
},
),
]

View File

@ -1,4 +1,27 @@
from django.db import models from django.db import models
from .validators import videoValidate, imageValidate
# def user_directory._path(instance, filename):
# print(request.user.id)
# return 'user_{0}/{1}'.format(instance.user.id, filename)
# Ok i got hella angry, so pleaSE fix this bullshit
# I want to be able to store each and every user's files in a separate folder, based on their id
# I CANT GET A FUCKING LOGGED IN USER ID FROM THE MODELS THINGY IM FUCKING PISSED
class Image(models.Model): class Image(models.Model):
image = models.FileField(upload_to='static/') title = models.CharField(max_length=200)
image = models.ImageField(upload_to=f"images/{upload_to}",validators=[imageValidate])
def __str__(self):
return self.title
class Videos(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to=f'videos/', validators=[videoValidate])
class Meta:
verbose_name = 'video'
verbose_name_plural = 'videos'
def __str__(self):
return self.title

View File

@ -0,0 +1,15 @@
def imageValidate(value):
import os
from django.core.exceptions import ValidationError
ext = os.path.splitext(value.name)[1]
valid_extensions = ['.jpg', '.png', '.gif']
if not ext.lower() in valid_extensions:
raise ValidationError('Unsupported file extension.')
def videoValidate(value):
import os
from django.core.exceptions import ValidationError
ext = os.path.splitext(value.name)[1]
valid_extensions = ['.mp4', '.mkv', '.avi']
if not ext.lower() in valid_extensions:
raise ValidationError('Unsupported file extension.')

View File

@ -1,8 +1,9 @@
from django.shortcuts import render, redirect from django.shortcuts import render, redirect
import os.path import os.path
from .forms import ImageForm from .forms import ImageForm, VideoForm
from django.core.files.storage import FileSystemStorage from django.core.files.storage import FileSystemStorage
def uploadContent(request): def uploadContent(request):
if request.method == "GET": if request.method == "GET":
return render(request, "uploadChoice.html") return render(request, "uploadChoice.html")
@ -24,15 +25,25 @@ def imageUpload(request):
if request.method == 'POST': if request.method == 'POST':
form = ImageForm(request.POST, request.FILES) form = ImageForm(request.POST, request.FILES)
if form.is_valid(): if form.is_valid():
myfile = request.FILES['image'] form.save()
fs = FileSystemStorage(location="./static/") #defaults to MEDIA_ROOT # Get the current instance object to display in the template
filename = fs.save(myfile.name, myfile) img_obj = form.instance
file_url = fs.url(filename) return render(request, 'uploadImage.html', {'form': form, 'img_obj': img_obj})
return render(request, 'uploadImage.html', {
'file_url': file_url,
'file_name': myfile.name,
})
else: else:
form = ImageForm() form = ImageForm()
return render(request, 'uploadImage.html', {'form': form})
def videoUpload(request):
"""Process videos uploaded by users"""
if request.method == 'POST':
form = VideoForm(request.POST, request.FILES)
if form.is_valid():
form.save()
img_obj = form.instance
return render(request, 'uploadVideo.html', {'form': form, 'img_obj': img_obj})
else:
form = VideoForm()
return render(request, 'uploadVideo.html', {'form': form})

View File

@ -40,7 +40,8 @@ INSTALLED_APPS = [
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'home', 'home',
'users', 'users',
'upload' 'upload',
] ]
MIDDLEWARE = [ MIDDLEWARE = [
@ -51,6 +52,7 @@ MIDDLEWARE = [
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
] ]
ROOT_URLCONF = 'website.urls' ROOT_URLCONF = 'website.urls'
@ -129,3 +131,6 @@ LOGOUT_REDIRECT_URL = "/"
EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend" EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend"
EMAIL_FILE_PATH = str(BASE_DIR.joinpath('sent_emails')) EMAIL_FILE_PATH = str(BASE_DIR.joinpath('sent_emails'))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

View File

@ -20,7 +20,7 @@ from django.conf import settings
from django.conf.urls.static import static from django.conf.urls.static import static
from django.contrib.auth import views from django.contrib.auth import views
from django.views.generic.base import TemplateView from django.views.generic.base import TemplateView
from upload.views import uploadContent, imageUpload from upload.views import uploadContent, imageUpload, videoUpload
urlpatterns = [ urlpatterns = [
path("", homePage, name='home'), path("", homePage, name='home'),
@ -28,8 +28,9 @@ urlpatterns = [
path("users/", include('django.contrib.auth.urls')), path("users/", include('django.contrib.auth.urls')),
path('users/', include('users.urls')), path('users/', include('users.urls')),
path("upload/", uploadContent, name="Upload"), path("upload/", uploadContent, name="Upload"),
path("upload_image/", imageUpload, name="Image") path("upload_image/", imageUpload, name="Image"),
path("upload_video/", videoUpload, name="Video"),
] ]
if settings.DEBUG: if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, urlpatterns += static(settings.MEDIA_URL,
document_root=settings.STATIC_ROOT) document_root=settings.MEDIA_ROOT)