Repository navigation
Conversation
- Update .gitignore to exclude media and backup directories - Implement UploadImageList and UploadImageDetail API views - Enhance UploadedImage model with primary image validation - Update serializers to include model_type and model_id fields - Modify DetailsImage component for image upload functionality - Integrate DetailsImageCarousel for displaying multiple images - Update PartDetail page to utilize new image handling features - Refactor ColumnRenderers to display primary image thumbnailsAdd image handling to Part model and create migration for UploadedImage
- Updated InvenTreeImageUploadMixin to delete images before the object deletion. - Modified UploadImageAdmin to display image in the admin list. - Added UploadImageThumbs API endpoint to retrieve thumbnails with usage count. - Introduced helper function to manage part image directory. - Created migration to transfer company images to Add UploadedImage model and API endpoints for image uploads - Update .gitignore to exclude media and backup directories - Implement UploadImageList and UploadImageDetail API views - Enhance UploadedImage model with primary image validation - Update serializers to include model_type and model_id fields - Modify DetailsImage component for image upload functionality - Integrate DetailsImageCarousel for displaying multiple images - Update PartDetail page to utilize new image handling features - Refactor ColumnRenderers to display primary image thumbnailsAdd image handling to Part model and create migration for UploadedImage
- Modified DetailsImage.tsx to include model_id and model_type in the download image form, ensuring proper handling of image uploads. - Adjusted the delete image functionality to set a backup image after deletion.
…d add search and filter options
✅ Deploy Preview for inventree-web-pui-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
There was a problem hiding this comment.
This is a good start; a few comments:
- I think
UploadedImageis a misleading name; all images are uploaded in some form so it should be justImage(maybeInvenTreeImage) - I think it would be better to use generic-relations instead of building your own choice and validation mechanisms as that enables easier use within plugins
- the removal of thumbnail in the apis makes no sense to me - why not link the thumbnail of the primary image and break less stuff?
- In a few places code is commented out instbeing beeing removed; not a fan of that, please clean that up
- os.path can have issues when switching between operating system, please use pathlib.Path - here is a conversion table https://docs.python.org/3/library/pathlib.html#corresponding-tools
Things to polish this a bit more:
- add a bit of docs for how images work
- add a control to the Admin Center to view and possibly remove images instead of the old django admin page
- add unit test (you already have that listed)
- update the description of your PR to describe how this change the api for users
| for part in Part.objects.all(): | ||
| if not part.image: | ||
| continue |
There was a problem hiding this comment.
Please just filter for parts that have images
There was a problem hiding this comment.
thanks! Got it. Will update soon.
| part.image.close() | ||
|
|
||
| # Extract the base filename to avoid path issues | ||
| filename = os.path.basename(part.image.name) |
There was a problem hiding this comment.
thanks! Got it. Will update soon.
| for company in Company.objects.all(): | ||
| if not company.image: | ||
| continue |
There was a problem hiding this comment.
Please use a filter on the object instead
There was a problem hiding this comment.
thanks! Got it. Will update soon.
| company.image.close() | ||
|
|
||
| # Extract the base filename to avoid path issues | ||
| filename = os.path.basename(company.image.name) |
There was a problem hiding this comment.
thanks! Got it. Will update soon.
| @admin.register(common.models.UploadedImage) | ||
| class UploadImageAdmin(admin.ModelAdmin): | ||
| """Admin interface for UploadedImage objects.""" | ||
|
|
||
| def formfield_for_dbfield(self, db_field, request, **kwargs): | ||
| """Provide custom choices for 'model_type' field.""" | ||
| if db_field.name == 'model_type': | ||
| db_field.choices = common.validators.get_model_options( | ||
| InvenTree.models.InvenTreeImageUploadMixin | ||
| ) | ||
|
|
||
| return super().formfield_for_dbfield(db_field, request, **kwargs) | ||
|
|
||
| list_display = ('model_type', 'model_id', 'image', 'primary') | ||
|
|
||
| search_fields = ('image',) | ||
| list_filter = ('model_type',) |
There was a problem hiding this comment.
We do not promote usage of the django admin anymore, please remove this
There was a problem hiding this comment.
I don't think "not promoting" means "not support" here - for ~20 LOC we get a low-level admin interface for free which does come in handy sometimes?
There was a problem hiding this comment.
thanks! Got it. Will update soon.
| type: ModelType.purchaseorder | ||
| })} | ||
| image={supplier.thumbnail || supplier.image} | ||
| image={supplier?.image.thumbnail || supplier?.image.image} |
There was a problem hiding this comment.
Does this mean there is no placeholder image anymore?
| {enableRevisionSelection && ( | ||
| <Stack gap='xs'> | ||
| <Text>{t`Select Part Revision`}</Text> | ||
| <RevisionSelector part={part} options={partRevisionOptions} /> | ||
| </Stack> | ||
| )} |
There was a problem hiding this comment.
You’re right, this was removed by mistake during a local merge. I’ll restore it immediately. Sorry about that.
| subtitle={subtitle} | ||
| imageUrl={order.customer_detail?.image} | ||
| subtitle={order.description} |
There was a problem hiding this comment.
You’re right, this was changed by mistake during a local merge. I’ll restore it immediately. Sorry about that.
| }) | ||
| .catch((error) => { | ||
| // Handle error | ||
| console.error('Error setting new image:', error); |
There was a problem hiding this comment.
thanks! Got it. Will update soon.
| const get_image_src = () => { | ||
| // Get primary image source | ||
| const primary_image = part?.images?.find( | ||
| (img: any) => img.primary === true | ||
| ); | ||
| return primary_image?.thumbnail ?? primary_image?.image; | ||
| }; |
There was a problem hiding this comment.
Question: Did you look into performance with many images?
There was a problem hiding this comment.
I see two options to optimize this:
- Add the primary image URL directly from the backend serializer.
- Use useMemo on the frontend to avoid re-computation.
I believe option 1 is the superior approach as it’s more performant and keeps the frontend logic cleaner.
useMemo would be more of a patch. Do you agree? I’ll proceed with the backend change.
There was a problem hiding this comment.
We use useMemo a lot, it is the right approach if you only can / want to touch the frontend.
As pointed out in the backend comments, I think the old (primary) image and thumbnail fields should be preserved so this would not be needed.
|
Also: This needs a new api revision - see https://docs.inventree.org/en/stable/develop/contributing/#api-versioning - and CI won't run till the conflicts are resolved |
| """Custom delete method for InvenTreeImageUploadMixin. | ||
|
|
||
| - Before deleting the object, check if there are any uploaded images associated with it. | ||
| - If so, delete the images first |
There was a problem hiding this comment.
Can an image be uploaded against multiple objects simultaneously? Or is it a single image-to-object association?
There was a problem hiding this comment.
The implementation allows for a many-to-many association, meaning an image can indeed be linked to multiple objects simultaneously via the “select existing image” feature.
It doesn't save duplicate images.
| @admin.register(common.models.UploadedImage) | ||
| class UploadImageAdmin(admin.ModelAdmin): | ||
| """Admin interface for UploadedImage objects.""" | ||
|
|
||
| def formfield_for_dbfield(self, db_field, request, **kwargs): | ||
| """Provide custom choices for 'model_type' field.""" | ||
| if db_field.name == 'model_type': | ||
| db_field.choices = common.validators.get_model_options( | ||
| InvenTree.models.InvenTreeImageUploadMixin | ||
| ) | ||
|
|
||
| return super().formfield_for_dbfield(db_field, request, **kwargs) | ||
|
|
||
| list_display = ('model_type', 'model_id', 'image', 'primary') | ||
|
|
||
| search_fields = ('image',) | ||
| list_filter = ('model_type',) |
There was a problem hiding this comment.
I don't think "not promoting" means "not support" here - for ~20 LOC we get a low-level admin interface for free which does come in handy sometimes?
|
|
||
| @cleanup.ignore | ||
| class UploadedImage(models.Model): | ||
| """Class which represents an uploaded image for Part and Company. |
There was a problem hiding this comment.
e.g.
"""Class which represents an uploaded image linked to another model instance."""| next_img = ( | ||
| UploadedImage.objects.filter( | ||
| model_type=self.model_type, model_id=self.model_id | ||
| ) |
There was a problem hiding this comment.
You probably also want to exclude the current ID from this filter - inside an atomic transaction, can we guarantee that the "self" ID hasn't been removed yet?
There was a problem hiding this comment.
Good catch. You’re right, I should exclude self.pk from the query to prevent a potential race condition. I’ll fix that. Thanks!
| image = InvenTree.serializers.InvenTreeImageSerializerField( | ||
| required=False, allow_null=True | ||
| ) | ||
| thumbnail = serializers.CharField(source='get_thumbnail_url', read_only=True) |
There was a problem hiding this comment.
This may cause issues because it is calling a function on each item in the dataset - we will need to carefully test that it does not execute a high number of database queries when performing a LIST API operation.
There was a problem hiding this comment.
You’re right to point out the risk of an N+1 query problem on list views.
I will investigate this.
There was a problem hiding this comment.
Happy to provide some pointers or assistance in this area, it's a very nuanced concept
There was a problem hiding this comment.
Thanks a lot, I really appreciate the offer! I’ll take an initial look myself, and will definitely ping you if I have any questions or could use some pointers. My initial thought was to use a tool like django-silk to profile the queries and check for optimization opportunities.
There was a problem hiding this comment.
Our dev setup already shops with a variety of tools and should alert you once you add a large enough test-dataset; they run during backend tests
There was a problem hiding this comment.
I’m encountering a test failure in part.test_api.PartDetailTests.test_part_operations related to an excessive number of database queries.
The failure occurs during the PATCH request to rename a part:
response = self.patch(url, {'name': 'a new better name'})
The test expects the operation to complete in fewer than 250 queries, but the test runner reports 346 queries, causing an AssertionError.
Here’s the interesting part: to investigate this, I manually performed the same part rename operation on a development server with django-silk enabled for profiling. Silk reported only 92 queries for the entire request.
This is a significant discrepancy, and it suggests the issue might be specific to the test environment’s query counting mechanism rather than the core logic of the rename operation itself.
There was a problem hiding this comment.
The test environment is staged with a reasonable amount of data to find o+1 issues. You will need to run silk with the test running to reproduce this; certainly sounds like something is iterating over parts.
There was a problem hiding this comment.
I found the problem it related to django-silk. :)
In test environment it count silk query also that cause excessive number of database queries
|
|
||
| def forwards(apps, schema_editor): | ||
| Company = apps.get_model('company', 'Company') | ||
| UploadedImage = apps.get_model('common', 'UploadedImage') |
There was a problem hiding this comment.
This migration must be in the "company" app, and it must be before the new 0076_remove_company_image migration file. Otherwise, the images may be deleted before this migration runs!
Alternatively, add this migration as a requirement for the 0076 migration in "company" app.
There was a problem hiding this comment.
thanks! Got it. Will update soon.
|
Excuse me, I have a trouble with images fields in PartBriefSerializer, My question is: What is the best practice in this scenario to resolve the N+1 issue? Should I go through every view/serializer that uses PartBriefSerializer and modify its queryset to use |
…nd update related methods; adjust image upload path in migration and handle remote image processing with error handling in serializer
|
I’m looking into updating our tests for the image management API. I see two possible approaches, and I’d like to get your opinion on which is better. Option 1: We could update the existing image-related tests within the Part application to be more comprehensive. Option 2: We could create a new, centralized test file at common/test_api.py and move all image-related tests there, making them more generic. What do you think is the best path forward? |
|
If the refactored PR is generic, it should have tests in common/; if there is still image-related code in part/ those parts should be covered by tests in the part/ directory. this will be easier to judge when there are no conflicts anymore and the CI is able to run through. You will be provided with a visual coverage breakdown and a clear list what parts of code still require coverage here in the PR by a bot |
…est cases; enhance image generation and validation in API
…across various serializers and APIs
…; streamline image handling and retrieval in serializers and frontend components
…e 'image' with 'thumbnail_url' and 'image_url' for consistency and improved retrieval
…deprecated methods, optimize image retrieval, and update related references for consistency
…s and API endpoints for new image architecture, and enhance related tests
|
Thank you for the feedback! Here’s a summary of the changes:
|
|
@Reza98Sh can you please address the merge conflicts before we starts another review round? |
|
Sure, I’ll address the merge conflicts and pull from master as soon as possible. |
…rt model - Incremented API version to 385 with new features and changes documented. - Removed 'image' field from Part model in migration 0143. - Cleaned up test cases related to image handling.
|
Conflicts resolved and branch updated. |
|
Thank you; if will wait for the CI and then run some on-prem tests |
|
It seems some tests have failed. My plan was to review and update all other the tests in the next PR, after the proposed implementation for images is approved. |
|
Excuse me, I am preparing for Hacktoberfest and I have several PRs planned for October (including this one). I would like to close this PR for now, fix all test failures, and then open a clean PR in October, so it will count for Hacktoberfest together with my other planned PRs. Would that be okay for you? |
|
Sure, go ahead |

Refactoring how "Images" are stored, moving to a single table approach.
Tasks
A new API namespace for images is introduced:
GET/api/image/POST/api/image/GET/api/image/<pk>/PATCH/api/image/<pk>/DELETE/api/image/<pk>/GET/api/image/thumbs/Demo
Screencast.from.2025-07-24.16-00-28.webm
Next Steps & Request for Feedback
This PR covers the core implementation of the new image storage architecture. The main logic, database changes, and UI updates are in place.
Before I proceed with updating the unit tests and update test database data, I would like to request a review of the current approach.
Could you please review the architecture and implementation to confirm if this is the desired direction?
Once the approach is approved, I will finalize the PR by completing the remaining tasks and ensuring full test coverage.
Thank you
Related Issues
Closes #9788