Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement complex validation logic for models?
I'm trying to implement a simple REST API for a geocaching app. each geocache has several stations once a geocache instance is created you should be able to append stations the stations of a geocache have a fixed order (implemented through position) if a new station gets inserted at a specific position, all subsequent stations should be shifted an operation like 4. should set the geocache flag released to False (not released geocaches should not be shown to the user) a geocache can only be released if there exists at least one station If have the following model. models.py class Geocache(models.Model): title = models.CharField(max_length=70) released = models.BooleanField(default=False) class Station(models.Model): class Meta: unique_together = (('geocache', 'position'),) ordering = ['geocache', 'position'] geocache = models.ForeignKey(Geocache, related_name='stations', on_delete=models.CASCADE) position = models.IntegerField() title = models.CharField(max_length=70) instruction = models.TextField() There are two cases I need to validate: Is the position of the new station in the range from 1 to ([highest position] + 1)? When a geocache gets updated and released = True, is there at least one station for that geocache? I having trouble where to put those validation checks. I am aware of three potential possibilities: Model-level validation (through clean-methods) what is no longer … -
Two-tier menu: shall I make a raw SQL query?
Django 3.2.6 class Menu(NameUniqueMixin, ArchivedMixin, models.Model): TYPE_CHOICES = [ (MenuTypes.TOP.value, MenuTypes.TOP.value), ] type = models.CharField(max_length=10, choices=TYPE_CHOICES) class MenuLevelOne(NameUniqueMixin, ArchivedMixin, models.Model): menu = models.ForeignKey(Menu, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) html = models.TextField(default="", blank=False, null=False) rank = models.PositiveIntegerField(default=0, null=False, unique=True, db_index=True, ) class MenuLevelTwo(NameUniqueMixin, ArchivedMixin, models.Model): level_one = models.ForeignKey(MenuLevelOne, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) html = models.TextField(default="", blank=False, null=False) rank = models.PositiveIntegerField(default=0, null=False, db_index=True, ) I'd like to make a tree-like menu. Like this: os \windows \linux hardware \motherboards \sound cards We can see here a two-tier menu. I can't imagine what is the best way to select data from the database. Of course, I am going to use a template as well. I'm going to make several queries to the database, then use a loop. And cache this all in the template. In other words: I'm planning to organize an owfully inefficient piece of code here and conceal it using cache. Or I'm also thinking of a custom SQL-query, which I don't like at all. Could you tell me what is the bast way to select data from the database in this case? And how a rough draft of template for this meny may look like? -
Delay saving a Django ImageField until after the object has a pk
I have a Django model for a Book which has a slug field that's a hash based on its pk. It also has a thumbnail which is saved to a path including that slug. In Admin, if I create and save the Book without a thumbnail, and then add the thumbnail and save the Book again, this works: the thumbnail is saved to /media/books/<slug>/foo.jpg. BUT if I create the Book with a thumbnail image, and save it, the thumbnail is saved before the slug can be generated, so it's saved to /media/books/foo.jpg. This because files are saved before the model. I'd like to always include slug in the thumbnail's path, but I can't work out how to delay saving the thumbnail until after the slug has been generated. Any ideas? from django.db import models from hashes import Hashids def upload_path(instance, filename): return "/".join([books, instance.slug, filename]) class Book(models.Model): title = models.CharField(null=False, blank=False, max_length=255) slug = models.SlugField(max_length=10, null=False, blank=True) thumbnail = models.ImageField( upload_to=upload_path, null=False, blank=True, default="" ) def save(self, *args, **kwargs): super().save(*args, **kwargs) if not self.slug: # Now we have a pk, generate a slug if it doesn't have one. hashids = Hashids(salt="my salt", min_length=5) self.slug = hashids.encode(self.pk) kwargs["force_insert"] = False self.save(*args, … -
Passing function arguments into django model instance
I have a function that saves model to database based on dictionary of items provided. def bulk_creator_product_segment(df_records): """ Create object in Product segment model Saves objects in bulk based on unique constraint """ model_instances = [models.Product_segment( name=record["SegmentName"], product_category=models.Product_category.objects.get(name=record["CategoryName"]), ) for record in df_records] models.Product_segment.objects.bulk_create(model_instances, ignore_conflicts=True) Now I am trying to make it reusable and move things that change to function arguments. However I am having a problem with converting the name and product_category which are model field into function argument, which would mean something like this: bulk_creator_product_segment(df_records, firstfield, secondfield): model_instances = [models.Product_segment( firstfield=record["SegmentName"], secondfield=models.Product_category.objects.get(name=record["CategoryName"]), ) for record in df_records] It will not read firstfield as argument but as field names in the Product_segment which is wrong. -
How to show data from django models whose boolean field is true?
verified = models.BooleanField(default=False) I want to show only that objects in frontend whose verified field is true in django models -
How to get data through an intermediate table?
There are three tables. class CustomUser(AbstractUser): phone_number = models.CharField(unique=True, max_length=10, null=True, blank=True) class SGroup(models.Model): id = models.BigAutoField(primary_key=True) group_name = models.CharField(max_length=25) password = models.CharField(max_length=25) class GroupUser(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) group = models.ForeignKey(NoteGroup, on_delete=models.CASCADE) color = models.CharField(max_length=6) As you can see it's classic many-to-many sql relationship (can't use django's one, cause need additional fields like 'color'). I need to get certain user's all SGroups (then to pass them to creation form of other instance). How can I achieve that? -
can not login in production /django
I successfully deployed my django webapp but now I am unable to login as superuser even if I put correct credentials Screenshot -
Django wsgi subprocess.Popen processes die on gunicorn restart
I'm currently working on the django project served by Nginx+gunicorn. One of the features of the application is to run and stop bots in the background. I have achieved it using the subprocess python module, but the problem is the process I start with the subprocess.Popen becomes a child process of the gunicorn and dies so far I restart the gunicorn. The code looks like this: subprocess.Popen( ['runbot'], close_fds=True, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) Where 'runbot' is a executable of the bot which is up and running until it receives the SIGTERM signal. The options close_fds and start_new_session do not help here and the process still starts as a child of the parent gunicorn process. Interesting observation - it seems to be it is a wsgi-related issue, since everything is working as expected when I start the project with the builtin django dev web-server. How can I use the subprocess.Popen with gunicorn and run the process completely detached on the linux system? Other options I consider are Start using Celery (but I'm not sure if it is suitable for startng/stopping daemons) Make use of systemctl --user, but there was a problem that user systemctl services die after user logs out from … -
why give this error message when creating migration to myapp(Django website)
Unhandled exception in thread started by .wrapper at 0x0446E7C8> Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise exception[1] File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management__init_.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "F:\python_project\05project\mywebsite\videorequest\models.py", line 4, in class Video(models.model): AttributeError: module 'django.db.models' has no attribute 'model' -
How can I Subtract Total Monthly Income from Total Monthly Expenditure to get Net Income using Python Django for loop and list index
I want to display Total Monthly Income, Total Monthly Expenditure and Net Income in Django template using a table. The idea is that; as the user continue to add Income and Expenditure on daily basis, the script should be able to add all the income for every month of the year and do the same thing on expenditure too. And Subtract the Total Monthly Expenditure from the Total Monthly Income to get the Net Income for every Month of every year inside the Models. The result of the calculation should be displayed accordingly in Django Template (E.g. Month = July 2021 - Total Monthly Income= 48,900, Total Monthly Expenditure= 9,500, Net Income=41,450). The problem here is that once there is no expenditure amount in the Expenditure Model, no result is displayed in the Django Template table even though there are many income figures in the Income Model, and whenever there are expenditure figures in the Expenditure Model, the Total Monthly Expenses switches to other Total Monthly Income, thereby giving a wrong Net Income. For example, if there are three months for different years, the Total Monthly Income results (First Column) are displayed correctly but the Total Monthly Expenditure (Second Column) … -
modelformset to display forms according to ModelChoiceField in django
I am first time implementing the django modelformsets. I have a ModelChoiceField with 4 choices - c1, c2, c3, c4 in a ModelForm MF. MF has 3 fields F1, F2 and F3, where F1 is the ModelChoiceField. And MF is used to create the modelformset. I want to display as many forms as the choices available in F1 using modelformset, in this case - 4 forms, one for each choice. And only that choice need to be available for selection in the ModelChoiceField. Rest choices are hidden. Is there any way I can achieve this? -
I want a left outer join of three tables
I want to do a 'Left outer join' based on 'PMP_MODEL' as shown in the SQL query below. SELECT A.PMP_MANU_NUM, A.PMP_MODEL_NM, A.PMP_TYPE, A.BORE, A.HEAD, A.CAPACITY ,B.VISIT_DATE, B.VISIT_ENGINEER_NM, B.VISIT_ENGINEER_PHONE, B.REPAIR_CONTENTS ,C.SITE_NUM, C.SITE_NM, C.SITE_ADDR ,D.MANU_COMP_NM, D.MANU_COMP_PHONE, D.DELI_COMP_NM, D.DELI_COMP_PHONE, D.MANU_DT, D.FREE_SRV_ST_DT, D.FREE_SRV_END_DT, D.PAID_SRV_COMP_NM, D.PAID_SRV_COMP_PHONE FROM PMP_MODEL A LEFT OUTER JOIN PMP_REPAIR_HISTORY B ON A.PMP_MANU_NUM = B.PMP_MANU_NUM LEFT OUTER JOIN SITE_INFO C ON A.PMP_MANU_NUM = C.PMP_MANU_NUM LEFT OUTER JOIN SITE_DETAIL_INFO D ON A.PMP_MANU_NUM = D.PMP_MANU_NUM WHERE A.PMP_MANU_NUM = ? ; I tried with 'select_related', but it doesn't work. class PmpModelList(APIView): def get(self, request, format = None): pmpList = PmpModel.objects.select_related('pmp_manu_num') serialize = PmpModelSerializer(pmpList, many = True) return Response(serialize.data) -
DRF : Custom child serializer to add a field from the parent
In my current model I have JSON field called "data", previously "foo" and "bar" fields was inside the JSON field. For performance reasons I had to externalize foo and bar to dedicated fields with a django migration. but i would like to keep the same endpoint format when reaching the API. Which means put "foo" and "bar" in the class DataSerializer(serializers.Serializer) How is it possible to share the data from FooModelSerializer() to the DataSerializer() ? endpoint output format: "results": [ { "id": 1 "data": { "json_field_A": "charValue", "json_field_B": 123, "json_field_C": "charValue", "foo": 12, "bar": "barValue" }, "other": 12345 }, { "id": 2 "data": { "json_field_A": "charValue", "json_field_B": 123, "json_field_C": "charValue", "foo": 12, "bar": "barValue" }, "other": 12345 } ] model : class FooModel(models.Model): data = models.JSONField( blank=False, null=False, default=some_default ) foo = models.IntegerField() bar = models.CharField() other = models.IntegerField() serializer : class DataSerializer(serializers.Serializer): json_field_A = fields.CharField() json_field_B = fields.IntegerField() json_field_C = fields.CharField() class FooModelSerializer(serializers.ModelSerializer): data = DataSerializer() class Meta: model = models.FooModel fields = ['id', 'data', 'other', 'foo', 'bar'] -
Django: Nested for loop do not work properly
We have two tables that have many to one relationships. in models.py : class Author(models.Model): name = models.CharField(max_length=100, null=False) username = models.CharField(max_length=35, null=False) def __str__(self): return self.name class Article(models.Model): CATEGOTY = ( ('programming', 'programming'), ('other', 'other') ) title = models.CharField(max_length=100, null=False) content = models.TextField(null=False) category = models.CharField(max_length=100, choices=CATEGOTY, null=False) creation = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title and in views.py: def articles(request): authors = Author.objects.all() articles = Article.objects.all() totalArticles = articles.count() authorAticles = Author.objects.annotate(numberOfArticles=Count('article')) return render(request, 'articles/article.html', { 'articles' : articles, 'authors' : authors, 'totalArticles': totalArticles, 'authorAticles': authorAticles }) and html code: <div class="container mb-3 p-3" id="author-aricle"> <div class="row"> <div class="col-sm"> totle articles: {{totalArticles}} </div> {% for author in authors %} <div class="col-sm"> {{author}}: {% for authorAticle in authorAticles %} {{authorAticle.numberOfArticles}} {% endfor %} articles </div> {% endfor %} </div> </div> I want the html output to display the number of articles by each author next to its name This means how many articles does each author have? I want the html output to be like this: author1: 2 articles author2: 3 articles author3: 3 articles etc but this does not happen and the output is: author1: 3 3 2 articles author2: 3 3 2 articles author3: … -
403 Forbidden making Ajax GET request to Django endpoint
Not really familiar with Ajax requests and am trying to learn about them. The following code is returning: GET http://127.0.0.1:8000/data/ 403 (Forbidden) jquery.min.js:2 views.py: def load_posts_data_view(request): qs = Post.objects.all() data = [] for obj in qs: item ={ 'id' : obj.id, 'title' : obj.title, 'body' : obj.body, 'author' : obj.author.user.username } data.append(item) return JsonResponse({'data':data}) urls.py: urlpatterns = [ path('data/', views.load_posts_data_view, name = 'posts-data'), ] main.js: $.ajax({ type: 'GET`', url: '/data/', success: function(response){ consoe.log(response); }, error: function(error){ console.log('error'); } }); On questions related to making POST requests, I see you have to provide a CSRF_TOKEN but I don't think I should have to do this when making a GET request? Can anyone help with this? -
Hiding html element clicked after ajax success
I'm new to Web Development and making a mock twitter application. I want the tweet box to be removed after I click on the delete button (only if it is actually deleted in the backend) I'm using django templating to loop through each tweet: {% for tweet in data%} <div class="container border border-primary rounded"> <p> tweet: {{tweet.content}}</p> <div class="row"> {{tweet.id}} <p class = "likes" style="margin: 0px 10px;"> likes: {{tweet.likes}} </p> <button class="btn btn-dark like" style="margin: 0px 10px;">like</button> <p class = "retweets" style="margin: 0px 10px;" > retweets: {{tweet.retweets}}</p> <button class = "btn btn-dark retweet" style="margin: 0px 10px;">retweet</button> <button class="btn btn-dark float-right delete_tweet" onclick="delete_tweet('{{tweet.id}}')">delete</button> </div> </div> {% endfor %} Here's the delete_tweet function: function delete_tweet(id){ $(document).ready(function(){ $.ajax({ url: "{% url 'deleteTweet'%}", data: {'id':id}, dataType: 'json', success: function(data){ console.log(data); $(this).parent().parent().remove(); } }); }); } This deletes the tweet in the backend fine, but the remove method doesn't work - I'm pretty sure that I'm this is not referring to the right scope, what should I be doing instead? -
403 Error when using Axios to post to Django
I am using a Django server connected to a React Native front end. The server works fine in my browser, but I get an error when trying to post in my app from Axios. I get the following error: [26/Aug/2021 13:26:53] "POST /api/ticket/ HTTP/1.1" 403 58 Forbidden: /api/ticket/ Here is my axios function: const getTicket = async function () { try { let res = await axios.post("http://127.0.0.1:8000/api/ticket/", { userID: 5, eventID: 1, }); return res; } catch (err) { console.error(err); return err; } }; Here is my models.py for the Ticket class: class Ticket(models.Model): ticketID = models.AutoField(primary_key=True) userID = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) eventID = models.ForeignKey( Event, related_name='tickets', on_delete=models.CASCADE) bookedAt = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.ticketID) Here is my TicketSerializer in serializers.py: class TicketSerializer(serializers.ModelSerializer): class Meta: model = Ticket fields = "__all__" My views.py class TicketViewSet(viewsets.ModelViewSet): queryset = Ticket.objects.all() serializer_class = TicketSerializer filter_backends = [DjangoFilterBackend] class MyTicketViewSet(viewsets.ModelViewSet): queryset = Ticket.objects.all() serializer_class = TicketSerializer def get_queryset(self): user = self.request.user return Ticket.objects.filter(userID=user) My urls.py router = DefaultRouter() router.register('ticket', TicketViewSet) router.register('myticket', MyTicketViewSet) urlpatterns = [ path('', include(router.urls)), ] What is confusing me is that more complex axios calls are working, such as this one below which correctly identifies the userid from the axios call … -
how to use django message framework for login required to show message
I am using @login required decorator in my most of views so what I want is to use message in my login page telling user if you want to open that page you have to login first so how I can achieve that I know I cannot achieve that on my views so anyone does that and know how to do please tell me how to achieve that if a user redirected to login because of @login required I want to show message please login to continue -
Created Model is not showing in Django Atomic Trasaction Block
Following code not working, it should increase count within the block itself: I am using django with mysql database. >>> len(ModelObject.objects.all()) 89 >>> with transaction.atomic(): ... ModelObject.objects.create(modelId="123") ... print(len(ModelObject.objects.all())) ... <ModelObject: ModelObject object (16125)> 89 >>> len(ModelObject.objects.all()) 90 -
Django handle files uploaded through React without letting users waiting
Apologies if the title is confusing. So, I'm trying to build a webapp where users upload some files through a React site, then once Django receives those files, it starts processing those files by calling some functions. However, the workload is quite heavy, it might take 3-5 mins for backend to finish the processing operation. I'd like to have the backend do its thing without letting the frontend user to wait. So, while the backend is processing those files, users can continue use the site however they want, and when the processing operation is done, there can be a snackbar or something to notify the front end user that the operation is done. Backend settings.py # Configure path to uploaded files DATA_ROOT = os.path.join(BASE_DIR, 'myapp/main/data') DATA_URL = 'data' Model: myproject/myapp/models.py class Document(models.Model): docfile = models.FileField(upload_to='') View: myproject/myapp/views.py I was thinking about using Python's async to do this, but wouldn't the return immediately kill the process? The upload function is just some slight modification of Django's documentation on how to handle uploaded files. # import a bunch of stuff... async def handle_uploaded_files(files): await process(files) def upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): files = request.FILES.getlist('ix_files') for file … -
DRF: Wrong content type recognition for CSV files when sending request by curl
I have a simple DRF view: @api_view(['post']) def test(request): file = request.FILES['file'] content_type = file.content_type return Response('ok') I'm making requests with curl. The problem is that when I send CSV file in request content type is not defined correctly. For example: curl --location -X POST \ -F 'file=@"file.csv"' \ 'http://localhost:8000/tasks/test' shows content type == 'application/octet-stream'. I would expect text/csv. But when I send png file content type is 'image/png'. How to force recognize content type when sending csv files correctly? -
Django Using attribute of queryset object
I create comments/messages area for my page. and I create like buttons for them too. When user enter the page I want show he default like button(Like or Unlike). If user is in the like list I want show he Unlike but I want to show the Like button if it is not in the list, that is, if it is not liked yet. Views: def detail_post(request,_detail): postDetail = UserPosts.objects.get(pk = _detail) #This is post messages = UserMessages.objects.all().filter(post_id =postDetail.id) #This is comment of post # I tried this but iit is not works for x in messages: total = x.like_message.all() print(total) context= { "detail":postDetail, "messages":messages, } Template: {% for message in messages %} {% if message.username_id == request.user.id %} <button class="btn btn-primary btn-sm" title="You can't like your message" disabled >Like</button> {% else %} <button class="btn btn-primary btn-sm text-white btn-like {{ message.id }} " type="submit" name="usermessages_id" value="{{ message.id }}" id="{{ message.id }}"> Like </button> {% endif %} {% endfor %} Here is the output of the for loop I wrote in the Views file: <QuerySet [<User: vahandag>]> <QuerySet [<User: vahandag>, <User: GladyaTH0R>, <User: user2>, <User: user3>, <User: vahandag1905>]> <QuerySet []> <QuerySet []> <QuerySet [<User: vahandag1905>]> <QuerySet [<User: vahandag1905>]> <QuerySet [<User: vahandag>]> … -
Direct graphql queries to DB READ Replicas
Want to direct graphql query requests to DB read replicas. We use a master slave architecture for DB(i.e. use master DB for write operations and several DB READ replicas for just reading data from DB). Since we use AWS RDS, the DB router puts a check on the type of request (POST vs GET) to forward the request to respective replica. GET requests are forwarded to DB READ REPLICAS while POST requests are forwarded to master DB. Now Graphql Queries use a POST request to read data from DB, reason being if graphql queries become large and complex they cannot be put in the GET request queryparams so a POST request is used to fetch data from DB. We would like to forward our graphql queries to READ replicas instead of master DB so that READ replica can be fully utilized and master DB is not overloaded. We plan to set some header in the request to do that. Will header setting work for our use case? If yes how do we do that in Django specifically for graphql queries. Any other ways to achieve this? -
geting more than one user in django
i created an app with referral system the challenge is that i want the referrer to see other models of his referred user say for example. investment platform i want the referrer to see the persons the refereed main account(a model) and investment status(a model). models class TheMain(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) main_balance = models.IntegerField(default=0) earning_balance = models.IntegerField(default=0) def __str__(self): return str(self.user) the referral returns more than one user class Referral(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) referral_balance = models.IntegerField(default=0) code = models.CharField(max_length=12, blank=True) referred_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="ref_by") updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user.username}- {self.code}' def get_reffered(self): qs = Referral.objects.all() my_refs = [] for reffered in qs: if reffered.referred_by == self.user: my_refs.append(reffered) return my_refs theviews referral = Referral.objects.get(user=request.user) my_ref = referral.get_reffered() refer_main = [] refer_invest =[] for my in my_ref: main = TheMain.objects.filter(user = my.user) for ma in main: refer_main.append(ma) print(f'this is the mama {ma} and amount funded{ma.main_balance}') the print statement returns all the referred name and amount paid Quit the server with CTRL-BREAK. this is the mama user1 and amount funded1100 this is the mama user2 and amount funded800 this is the mama user and amount funded400. the problem is loooping all these users … -
django, upload tif image
I am trying to upload a tif image (greyscale), using django ImageField. I have installed Pillow==8.3.1 and using Python 3.9. The app works only with PNG/JPEG images. Here is the model I am using: class Upload(models.Model): image = models.ImageField(upload_to='images') title = models.CharField(max_length=200) action = models.CharField(max_length=50,choices=ACTION_CHOICES) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title #breakpoint() # def __str__(self): # pixels = tfi.imread(self.image) # return np.shape(np.array(pixels)) def save(self,*args,**kwargs): #open image #breakpoint() if self.action=='tif': pixels = tfi.imread(self.image) else: pixels = Image.open(self.image) #pixels = tfi.imread(self.image) pixels = np.array(pixels) pixels=pixels[:,:,0] #pixels = pixels[0,:,:] #use the normalisation method img = get_image(pixels) im_pil=Image.fromarray(img) #save buffer = BytesIO() im_pil.save(buffer,format='png') image_png = buffer.getvalue() self.image.save(str(self.image), ContentFile(image_png),save=False) super().save(*args,**kwargs) #return self.image_png