Skip to content

Commit 1229f53

Browse files
committed
Check http accept header for json, and use id fields for delete
1 parent 3e5b1f0 commit 1229f53

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

fileupload/urls.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@
33

44
urlpatterns = patterns('',
55
(r'^new/$', PictureCreateView.as_view(), {}, 'upload-new'),
6-
(r'^delete/(?P<slug>.+)$', PictureDeleteView.as_view(), {}, 'upload-delete'),
6+
(r'^delete/(?P<pk>\d+)$', PictureDeleteView.as_view(), {}, 'upload-delete'),
77
)
88

fileupload/views.py

+14-4
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,35 @@
77

88
from django.conf import settings
99

10+
def response_mimetype(request):
11+
if "application/json" in request.META['HTTP_ACCEPT']:
12+
return "application/json"
13+
else:
14+
return "text/plain"
15+
1016
class PictureCreateView(CreateView):
1117
model = Picture
1218

1319
def form_valid(self, form):
1420
self.object = form.save()
1521
f = self.request.FILES.get('file')
16-
data = [{'name': f.name, 'url': settings.MEDIA_URL + "pictures/" + f.name, 'thumbnail_url': settings.MEDIA_URL + "pictures/" + f.name, 'delete_url': reverse('upload-delete', args=[f.name]), 'delete_type': "DELETE"}]
17-
return JSONResponse(data)
22+
data = [{'name': f.name, 'url': settings.MEDIA_URL + "pictures/" + f.name, 'thumbnail_url': settings.MEDIA_URL + "pictures/" + f.name, 'delete_url': reverse('upload-delete', args=[self.object.id]), 'delete_type': "DELETE"}]
23+
return JSONResponse(data, {}, response_mimetype(self.request))
1824

1925
class PictureDeleteView(DeleteView):
2026
model = Picture
2127

2228
def delete(self, request, *args, **kwargs):
29+
"""
30+
This does not actually delete the file, only the database record. But
31+
that is easy to implement.
32+
"""
2333
self.object = self.get_object()
2434
self.object.delete()
25-
return JSONResponse(True)
35+
return JSONResponse(True, {}, response_mimetype(self.request))
2636

2737
class JSONResponse(HttpResponse):
28-
"""JSON response class. This does not help browsers not liking application/json."""
38+
"""JSON response class."""
2939
def __init__(self,obj='',json_opts={},mimetype="application/json",*args,**kwargs):
3040
content = simplejson.dumps(obj,**json_opts)
3141
super(JSONResponse,self).__init__(content,mimetype,*args,**kwargs)

0 commit comments

Comments
 (0)