|
1 | 1 | import secrets
|
| 2 | +import os |
2 | 3 |
|
3 | 4 | from django.conf import settings
|
4 | 5 | from django.contrib.auth import get_user_model
|
| 6 | +from django.core.files.storage import default_storage |
5 | 7 |
|
6 | 8 | from classroom.tasks import send_temp_password_for_new_students_task
|
7 | 9 |
|
@@ -73,19 +75,15 @@ def resend_password_emails(classroom, email):
|
73 | 75 | )
|
74 | 76 |
|
75 | 77 |
|
76 |
| -def upload_reading_exercise_image(image, request=None): |
77 |
| - path = settings.MEDIA_ROOT / 'classroom' / 'reading_exercises' / 'uploaded_images' / image.name |
78 |
| - path.parent.mkdir(parents=True, exist_ok=True) |
79 |
| - if path.exists(): |
80 |
| - unique_name = path.stem + secrets.token_urlsafe(nbytes=8) |
81 |
| - path = path.parent / f'{unique_name}{path.suffix}' |
| 78 | +def upload_reading_exercise_image(image): |
| 79 | + directory = 'classroom/reading_exercises/uploaded_images' |
| 80 | + path = f'{directory}/{image.name}' |
82 | 81 |
|
83 |
| - with open(path, 'wb+') as destination: |
84 |
| - for chunk in image.chunks(): |
85 |
| - destination.write(chunk) |
| 82 | + if default_storage.exists(path): |
| 83 | + img_name, img_ext = os.path.splitext(image.name) |
| 84 | + unique_name = img_name + secrets.token_urlsafe(nbytes=8) |
| 85 | + path = f'{directory}/{unique_name}{img_ext}' |
86 | 86 |
|
87 |
| - rpath = path.relative_to(settings.BASE_DIR) |
88 |
| - url = '/' + str(rpath).replace('\\', '/') |
89 |
| - if request: |
90 |
| - url = request.build_absolute_uri(url) |
| 87 | + default_storage.save(path, image) |
| 88 | + url = default_storage.url(path) |
91 | 89 | return url
|
0 commit comments