Added avatar profile uploads

This commit is contained in:
Keannu Bernasol 2023-07-27 16:00:24 +08:00
parent fd2563aff9
commit e9d4090713
3 changed files with 21 additions and 2 deletions

View file

@ -8,6 +8,8 @@ from semesters.models import Semester
from django.db.models.signals import post_migrate
from django.dispatch import receiver
import os
from uuid import uuid4
from django.utils.deconstruct import deconstructible
def validate_student_id(value):
@ -18,13 +20,28 @@ def validate_student_id(value):
class CustomUser(AbstractUser):
# Function for avatar uploads
def _get_upload_to(instance, filename):
base_filename, file_extension = os.path.splitext(filename)
# Get the student ID number
ext = base_filename.split('.')[-1]
filename = '{}.{}'.format(uuid4().hex, ext)
student_id = str(instance.student_id_number)
new_filename = f"{student_id}_{file_extension}"
new_filename = f"{student_id}_{filename}_{file_extension}"
return os.path.join('avatars', new_filename)
# Delete old avatar file if new one is uploaded
def save(self, *args, **kwargs):
try:
# is the object in the database yet?
this = CustomUser.objects.get(id=self.id)
if this.avatar != self.avatar:
this.avatar.delete(save=False)
except:
pass # when new photo then we do nothing, normal case
super(CustomUser, self).save(*args, **kwargs)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
# Email inherited from base user class

View file

@ -16,6 +16,7 @@ from django.contrib.gis.geos import Point
from django.utils.encoding import smart_str
from drf_spectacular.utils import extend_schema_field
from drf_spectacular.types import OpenApiTypes
from drf_extra_fields.fields import Base64ImageField
# There can be multiple subject instances with the same name, only differing in course, year level, and semester. We filter them here
@ -46,6 +47,7 @@ class CustomUserSerializer(BaseUserSerializer):
# Use custom slug field for filtering
subjects = SubjectSlugRelatedField(
many=True, slug_field='name', queryset=Subject.objects.all(), required=False)
avatar = Base64ImageField()
class Meta(BaseUserSerializer.Meta):
model = CustomUser

View file

@ -28,7 +28,7 @@ BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = str(os.getenv('SECRET_KEY'))
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
DEBUG = True
FRONTEND_DEBUG = False
ALLOWED_HOSTS = ['*']