forum: factor attachment creation code

This commit is contained in:
Lephe 2022-05-26 20:08:01 +01:00
parent 84066eaca3
commit 6756838882
Signed by: Lephenixnoir
GPG Key ID: 1BBA026E13FC0495
3 changed files with 16 additions and 22 deletions

View File

@ -1,5 +1,6 @@
from app import db
from app.models.post import Post
from app.models.attachment import Attachment
from sqlalchemy.orm import backref
@ -54,5 +55,17 @@ class Comment(Post):
db.session.commit()
db.session.delete(self)
def create_attachments(self, multiple_file_field_data):
"""Create attachements from a form's MultipleFileField.data."""
attachments = []
for file in multiple_file_field_data:
if file.filename != "":
a = Attachment(file, self)
attachments.append((a, file))
db.session.add(a)
db.session.commit()
for a, file in attachments:
a.set_file(file)
def __repr__(self):
return f'<Comment: #{self.id}>'

View File

@ -46,17 +46,7 @@ def forum_topic(f, page):
c = Comment(author, form.message.data, t.thread)
db.session.add(c)
db.session.commit()
# Manage files
attachments = []
for file in form.attachments.data:
if file.filename != "":
a = Attachment(file, c)
attachments.append((a, file))
db.session.add(a)
db.session.commit()
for a, file in attachments:
a.set_file(file)
c.create_attachments(form.attachments.data)
# Update member's xp and trophies
if current_user.is_authenticated:

View File

@ -1,4 +1,5 @@
from app import app, db
from app.models.user import Guest
from app.models.program import Program
from app.models.comment import Comment
from app.models.thread import Thread
@ -32,17 +33,7 @@ def program_view(page):
c = Comment(author, form.message.data, p.thread)
db.session.add(c)
db.session.commit()
# Manage files
attachments = []
for file in form.attachments.data:
if file.filename != "":
a = Attachment(file, c)
attachments.append((a, file))
db.session.add(a)
db.session.commit()
for a, file in attachments:
a.set_file(file)
c.create_attachments(form.attachments.data)
# Update member's xp and trophies
if current_user.is_authenticated: