diff --git a/rhinventory/admin_views/file.py b/rhinventory/admin_views/file.py index 9a0285b..e923dfa 100644 --- a/rhinventory/admin_views/file.py +++ b/rhinventory/admin_views/file.py @@ -96,7 +96,7 @@ def details_view(self): if id is None: return redirect(return_url) - model = self.get_one(id) + model: File | None = self.get_one(id) if model is None: flash('Record does not exist.', 'error') @@ -116,7 +116,12 @@ def details_view(self): file_assign_form.process(request.form) if request.method == "POST" and file_assign_form.validate(): - model.assign(file_assign_form.asset.data) + try: + model.assign(file_assign_form.asset.data) + except ValueError as e: + flash(f"Failed to assign file to asset: {e}", 'error') + return redirect(url_for("file.details_view", id=id)) + db.session.add(model) log("Update", model, user=current_user) db.session.commit() @@ -184,7 +189,12 @@ def upload_view(self): else: asset_ids = [File.read_rh_barcode(file) for file in image_files] for file, asset_id in zip(image_files, asset_ids): - file.assign(asset_id) + try: + file.assign(asset_id) + except ValueError: + # Probably failed to assign file to asset because asset doesn't exist + # Ignore this + pass print("Creating thumbnails...") # Create thumbnails in parallel @@ -314,11 +324,20 @@ def rotate_view(self): @require_write_access def assign_view(self): id = get_mdict_item_or_list(request.args, 'id') - model = self.get_one(id) + model: File | None = self.get_one(id) + if not model: + flash('Record does not exist.', 'error') + return redirect(url_for("file.details_view", id=id)) asset_id = get_mdict_item_or_list(request.args, 'asset_id') + assert isinstance(asset_id, int) - model.assign(asset_id) + try: + model.assign(asset_id) + except ValueError as e: + flash(f"Failed to assign file to asset: {e}", 'error') + return redirect(url_for("file.details_view", id=id)) + db.session.add(model) log("Update", model, user=current_user) db.session.commit() diff --git a/rhinventory/models/file.py b/rhinventory/models/file.py index a550eee..a00afb2 100644 --- a/rhinventory/models/file.py +++ b/rhinventory/models/file.py @@ -242,10 +242,19 @@ def auto_assign(self): if asset_id: self.assign(asset_id) - def assign(self, asset_id): + def assign(self, asset_id: int): '''Assigns File to a given Asset and renames file and thumbnail''' + + from rhinventory.models.asset import Asset # avoid circular import + if not asset_id: return + + # check that asset exists + asset = Asset.query.get(asset_id) + if not asset: + raise ValueError("Trying to assign to asset that does not exist") + self.asset_id = asset_id files_dir = current_app.config['FILE_STORE_LOCATIONS'][self.storage.value]