Refactor Extension and Version: explicit constructors from File #191

Merged
Oleg-Komarov merged 6 commits from refactor-models into main 2024-06-20 14:40:41 +02:00
3 changed files with 11 additions and 6 deletions
Showing only changes of commit 1df59f7a10 - Show all commits

View File

@ -65,7 +65,7 @@ def create_version(**kwargs) -> 'Version':
file = FileFactory(**kwargs)
if not extension:
extension = Extension.create_from_file(file, file.user)
extension = Extension.create_from_file(file)
return extension.create_version_from_file(file)

View File

@ -186,11 +186,11 @@ class Extension(CreatedModifiedMixin, TrackChangesMixin, models.Model):
ordering = ['-average_score', '-date_created', 'name']
@classmethod
def create_from_file(cls, file: File, author: User) -> 'Extension':
def create_from_file(cls, file: File) -> 'Extension':
extension = cls(**file.parsed_extension_fields)
with transaction.atomic():
extension.save()
extension.authors.add(author)
extension.authors.add(file.user)
return extension
def create_version_from_file(self, file: File, release_notes='') -> 'Version':

View File

@ -36,8 +36,13 @@ class UploadFileView(LoginRequiredMixin, CreateView):
def form_valid(self, form):
"""Create an extension and a version already, associated with the user."""
file = form.save()
# TODO understand if file.user can ever be different from self.request.user
# e.g. if reusing an already uploaded file?
self.extension = Extension.create_from_file(file, self.request.user)
if file.user != self.request.user:
# this must never happen, but checking here to prevent misattributing the extension
# to a wrong user
raise Exception(
f'user {self.request.user} uploaded a file hash={file.hash} owned by {file.user}, '
f'this must never happen'
)
self.extension = Extension.create_from_file(file)
self.extension.create_version_from_file(file)
return super().form_valid(form)