def edit_image(request): if request.method != 'POST': return redirect(main_map) context = {} errs = [] context['errors'] = errs # Get lat/lng/caption data lat = request.POST.get('lat') lng = request.POST.get('lng') caption = request.POST.get('caption') im_id = request.POST.get('img_id') albums_str = request.POST.get('edit-album') # Parse albums string into array of ints try: albums = [int(s) for s in albums_str.split(',')] except: albums = [] username = request.user.username image,errors = Image.update(im_id=im_id, username=username, lat=lat, lng=lng, caption=caption, albums=albums) context['image'] = image if errors: print(errors) errs.extend(errors) else: context['message'] = "Image successfully updated!" return render(request, 'json/upload_response.json', context, content_type="application/json")
def patch_image(request): try: data = json.loads(request.body.decode('utf-8')).get('data') except: return JsonResponse(bad_format_errors(["Could not parse JSON body"]), status=400) if not data: return JsonResponse(bad_format_errors(["Missing 'data' component of request"]), status=400) api_key = request.GET.get('api_key') # Does this api key exist? try: profile = Profile.objects.get(api_key=api_key) except: return JsonResponse(bad_api_key_error, status=403) image_id = data.get('id') # Try to get image with this id try: image = Image.objects.get(id=image_id) except: return JsonResponse(not_found_error("Image not found"), status=404) # If incorrect user, return not found if image.user != profile.user: return JsonResponse(not_found_error("Image not found"), status=404) # Retrieve attribute data attributes = data.get('attributes', {}) lat = attributes.get('lat') lng = attributes.get('lng') caption = attributes.get('caption', None) # Retrieve new album data relationships = data.get('relationships') if relationships: album_diff = relationships.get('albums', {}) add = album_diff.get('add', []) remove = album_diff.get('remove', []) try: curr_album_ids = image.album_ids() add_ids = [a.get('id') for a in add if a.get('id') not in curr_album_ids] remove_ids = [a.get('id') for a in remove] # Add new elements to list curr_album_ids.extend(add_ids) # Remove elements to remove album_ids = [x for x in curr_album_ids if x not in remove_ids] except: return JsonResponse(bad_format_errors(["Malformed 'album' relationship objects"]), status=400) else: album_ids = image.album_ids() image,errs = Image.update(im_id=image_id, username=profile.user.username, lat=lat, lng=lng, caption=caption, albums=album_ids) if errs: return JsonResponse(bad_format_errors(errs), status=400) # Create response object context = { 'data': image.as_dict(True,True) } return JsonResponse(context)