Skip to content

Commit

Permalink
Check http accept header for json, and use id fields for delete
Browse files Browse the repository at this point in the history
  • Loading branch information
sigurdga committed Jul 13, 2011
1 parent 3e5b1f0 commit 1229f53
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
2 changes: 1 addition & 1 deletion fileupload/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@

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

18 changes: 14 additions & 4 deletions fileupload/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,35 @@

from django.conf import settings

def response_mimetype(request):
if "application/json" in request.META['HTTP_ACCEPT']:
return "application/json"
else:
return "text/plain"

class PictureCreateView(CreateView):
model = Picture

def form_valid(self, form):
self.object = form.save()
f = self.request.FILES.get('file')
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"}]
return JSONResponse(data)
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"}]
return JSONResponse(data, {}, response_mimetype(self.request))

class PictureDeleteView(DeleteView):
model = Picture

def delete(self, request, *args, **kwargs):
"""
This does not actually delete the file, only the database record. But
that is easy to implement.
"""
self.object = self.get_object()
self.object.delete()
return JSONResponse(True)
return JSONResponse(True, {}, response_mimetype(self.request))

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

0 comments on commit 1229f53

Please sign in to comment.