1+ from django .http import JsonResponse
12from django .shortcuts import render , redirect
3+ from django .views .decorators .csrf import csrf_exempt
4+ from django .conf import settings
5+
6+ from djang_website .settings import MEDIA_URL
7+
28from .models import Article , ArticleSeries
39from .decorators import user_is_superuser
410from .forms import SeriesCreateForm , ArticleCreateForm , SeriesUpdateForm , ArticleUpdateForm
511
12+ import os
13+ from uuid import uuid4
14+
615# Create your views here.
716def homepage (request ):
817 matching_series = ArticleSeries .objects .all ()
@@ -153,4 +162,34 @@ def article_delete(request, series, article):
153162 "object" : matching_article ,
154163 "type" : "article"
155164 }
156- )
165+ )
166+
167+ @csrf_exempt
168+ @user_is_superuser
169+ def upload_image (request , series , article ):
170+ if request .method != 'POST' :
171+ return JsonResponse ({"Error Message" : "Wrong request" })
172+
173+ matching_article = Article .objects .filter (series__slug = series , article_slug = article ).first ()
174+ if not matching_article :
175+ return JsonResponse ({"Error Message" : f"Wrong series({ series } ) or article ({ article } )" })
176+
177+ file_obj = request .FILES ['file' ]
178+ file_name_suffix = file_obj .name .split ('.' )[- 1 ]
179+ if file_name_suffix not in ['jpg' , 'png' , 'gif' , 'jpeg' ]:
180+ return JsonResponse ({"Error Message" : f"Wrong file suffix ({ file_name_suffix } ), supported are .jpg, .png, .git, .pjeg" })
181+
182+ file_path = os .path .join (settings .MEDIA_ROOT , 'ArticleSeries' , matching_article .slug , file_obj .name )
183+
184+ if os .path .exists (file_path ):
185+ file_obj .name = str (uuid4 ()) + '.' + file_name_suffix
186+ file_path = os .path .join (settings .MEDIA_ROOT , 'ArticleSeries' , matching_article .slug , file_obj .name )
187+
188+ with open (file_path , 'wb+' ) as f :
189+ for chunk in file_obj .chunks ():
190+ f .write (chunk )
191+
192+ return JsonResponse ({
193+ "Message" : "Image upload successfully" ,
194+ "location" : os .path .join (settings .MEDIA_URL , 'ArticleSeries' , matching_article .slug , file_obj .name )
195+ })
0 commit comments