Skip to content
Snippets Groups Projects
models.py 1.66 KiB
Newer Older
from django.db import models
from django.core import validators
from django.dispatch import receiver
from account.models import Profile
from homework.models import Solution
from common.validators import FileSizeValidator
Rafael László's avatar
Rafael László committed
from common.middleware import CurrentUserMiddleware

def document_file_name(instance, filename):
    return '/'.join([
        'document',
        instance.solution.task.title,
        instance.uploaded_by.full_name,
        filename
    ])


class Document(models.Model):
Rafael László's avatar
Rafael László committed
    uploaded_by = models.ForeignKey(
        Profile,
        on_delete=models.DO_NOTHING,
        related_name='documents',
        default=CurrentUserMiddleware.get_current_user_profile,
    )
    uploaded_at = models.DateTimeField(auto_now_add=True, editable=False)
Bodor Máté's avatar
Bodor Máté committed
    name = models.CharField(max_length=150, blank=True, default='')
Bodor Máté's avatar
Bodor Máté committed
    description = models.TextField(blank=True, default='')
    file = models.FileField(
        validators=[
            validators.FileExtensionValidator([
                'png',
                'jpeg',
                'jpg',
                'zip',
            ]),
            FileSizeValidator(size_limit=52428800),  # 52428800 - 50MiB
        ],
        blank=True,
        null=True,
        upload_to=document_file_name
Bodor Máté's avatar
Bodor Máté committed
    solution = models.ForeignKey(Solution, related_name='files', on_delete=models.CASCADE)

    def __str__(self):
        return self.name


# Deletes file from filesystem when File object is deleted.
@receiver(models.signals.post_delete, sender=Document)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    if instance.file:
        if os.path.isfile(instance.file.path):
            os.remove(instance.file.path)