Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS beanstalk deployment failed with exit status 1
I've been trying for several days now to set up Django under Amazon Web Services' Elastic Beanstalk. I am getting two error most of the time: 1.ERROR - Your WSGIPath refers to a file that does not exist. 2.ERROR: Your requirements.txt is invalid. Snapshot your logs for details. Here's directory structure: βββ .ebextensions β βββ django.config βββ .elasticbeanstalk β βββ config.yml βββ .git βββ .gitignore βββ manage.py βββ saleor β βββ __init__.py β βββ settings.py β βββ urls.py β βββ wsgi.py βββ requirements.txt Here is django.config file inside .ebextensions: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: saleor/wsgi.py packages: yum: gcc: [] python36-devel: [] gcc-c++: [] libffi-devel: [] postgresql93-devel: [] Error: ------------------------------------- /var/log/eb-activity.log ------------------------------------- File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/sandbox.py", line 47, in _execfile exec(code, globals, locals) File "/tmp/easy_install-q1ck81sr/cffi-1.11.5/setup.py", line 240, in <module> File "/usr/lib64/python3.6/distutils/core.py", line 163, in setup raise SystemExit("error: " + str(msg)) SystemExit: error: command 'gcc' failed with exit status 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 1101, in run_setup run_setup(setup_script, args) File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/sandbox.py", line 251, in run_setup raise File "/usr/lib64/python3.6/contextlib.py", line 99, in __exit__ self.gen.throw(type, value, traceback) File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/sandbox.py", line 198, in setup_context yield File "/usr/lib64/python3.6/contextlib.py", line 99, in __exit__ self.gen.throw(type, value, traceback) File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/sandbox.py", β¦ -
View from forked django-oscar app not returning any data to template
I have forked the django-oscar catalogue app to alter the models being used. Not in a major way, and not in a way that would affect pulling data from the database as far as I can see. This seems to be supported by the fact the the django-oscar dashboard still works fine and lets me add and view products. My models.py from my forked app: from django.db import models class Collection(models.Model): name = models.CharField(max_length=50) prod_category = models.CharField(max_length=50) description = models.TextField() manufacturer = models.TextField() num_products = models.PositiveIntegerField() image_url = models.URLField() from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): collection = models.ForeignKey(Collection, on_delete=models.CASCADE, null=True) multiplier = models.DecimalField(max_digits=2, decimal_places=1, default='2.2') from oscar.apps.catalogue.models import * Here is my relevant view from my views.py def product(request): template = loader.get_template('/home/my_app/furniture_site/main_page/templates/main_page/product.html') prods = Product.objects.values_list('categories') context={'prods': prods} return HttpResponse(template.render(context)) I tried loading from the built in model and my forked model (commenting and uncommenting one or both), neither makes a difference: #from forkedoscarapps.catalogue.models import Product from oscar.core.loading import get_class, get_model Product = get_model('catalogue', 'product') And the code I am using in the template to display data from the view: {% for instance in prods %} <li><{{ instance.name }}</li> {% endfor %} There is at least one category called beds, which β¦ -
Django Elastic-Search Integration Problems
im currently trying to implement elasticsearch on my app to search trough my posts. currently im doing this trough a direct query against the Postgres DB. urls.py ... #url(r'^search/$', myproject_views.globalsearch_local.as_view(), name='search'), # Use a local Search function (small-setup) url(r'^search/$', myproject_views.globalsearch_elastic, name='search'), # Use Elasticsearch (large-scale-setup) ... base.html (q as search input) ... <div class="globalsearch"> <form id="searchform" action="{% url 'search' %}" method="get" accept-charset="utf-8"> <label for="{{ categorysearch_form.category.id_for_label }}"></label><br> <div class="form-row align-items-center"> <div class="custom-dropdown">{{ categorysearch_form.category }}</div> <input class="class-search-input-fields" id="searchbox" name="q" required="required" type="text" placeholder="Search myproject"> <button class="btn btn-dark" type="submit"> <i class="fa fa-search"></i> </button> <div class="category-globalsearch"> ... views.py (search views) ... # Use Elasticsearch (large-scale-setup) def globalsearch_elastic(request): qs = request.GET.get('q') if qs: posts = PostDocument.search().query("match", titel=qs) else: posts = '' for post in posts: print(post) return render(request, 'myproject/search_results.html', {'object_list':posts}) # Use a local Search function (small-setup) class globalsearch_local(ListView): """ Display a Post List page filtered by the search query. """ model = Post paginate_by = 10 template_name = 'myproject/search_results.html' def get_queryset(self): keywords = self.request.GET.get('q') if keywords: query = SearchQuery(keywords) title_vector = SearchVector('title', weight='A') content_vector = SearchVector('content', weight='B') tag_vector = SearchVector('tag', weight='C') vectors = title_vector + content_vector + tag_vector qs = Post.objects.annotate(rank=SearchRank(vectors, query)).filter(rank__gte=0.1).order_by('-rank') return qs seetings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', β¦ -
django blog error keeps occuring on deployment to heroku
I am getting the following error when I try open my blog page after deployment to Heroku. it works ok in cloud9 but throws up the error once I deploy it. All the other pages of the site work fine. Can anybody help me please? [ Blog models.py file from django.db import models from django.utils import timezone from django.urls import reverse from django.conf import settings from django.contrib.auth.models import User from django.db.models.signals import pre_save from django.utils.text import slugify import datetime class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='user') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to='images', default='Upload Picture') category = models.CharField(max_length=200) description = models.CharField(max_length=340) views = models.IntegerField(default=0) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='post_likes', blank=True) def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse('post_detail', kwargs={"slug": self.slug}) def get_like_url(self): return reverse('like', kwargs={"slug": self.slug}) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse("post_list") def __str__(self): return self.text -
How to run a Django shell command from a script outside the Django project
I have a web scraper. It outputs JSON data. I have a Django project that uses this JSON data. These are in two separate repos/directories. My scraper copies the data file into my Django project. What I want is for that scraper script to then run my custom command, which I would usually activate in the command line with: python manage.py load_concerts name_of_file.json How do I make my scraper script (which again, is outside of the Django project) run the commands? (Googling these search terms is giving me people asking the opposite question, asking how to run a python script from the command line. I want to run a command prompt from a python script.) -
LOGIN_REDIRECT_URL not working in django2.1
i am learning django and i am having hard time integrating built-in django login systems. In settings.py i have provided LOGIN_REDIRECT_URL AND LOGOUT_REDIRECT_URL here, LOGOUT_REDIRECT_URL is working fine when i click Logout button. Button LOGIN_REDIRECT_URL is not working when i have provided with login credentials. settings.py LOGOUT_REDIRECT_URL = 'post_list' LOGIN_REDIRECT_URL = 'post_list' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] urls.py from django.urls import path, include from django.contrib import admin urlpatterns = [ path(r'admin/', admin.site.urls), path(r'', include('blog.urls')), ] blog/urls.py from django.urls import path from .views import (BlogListView, BlogDetailView, BlogCreateView, BlogUpdateView, BlogDeleteView) urlpatterns = [ path('', BlogListView.as_view(), name='post_list'), path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), path('post/new/', BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'), path('post/<int:pk>/delete/', BlogDeleteView.as_view(), name='post_delete'), ] login.html {% extends 'base.html' %} {% block content %} <h2>Login</h2> <form action="post"> {% csrf_token %} {{form.as_p}} <button type='submit'>Login</button> </form> {% endblock %} base.html <body> <div class="container"> <header> <div class="nav-left"> <h1><a href="/">Django Blog</a></h1> </div> <div class=nav-right> <a href="{% url 'post_new' %}"> + New Blog Post. </a> </div> </header> {% if user.is_authenticated %} <p>Hi! {{user.username}}</p> <a href="{% url 'logout' %}">Logout</a> {% else %} <p>You are not logged in. </p> <a href="{% url 'login' %}">Login</a> {% endif %} {% block content %} {% endblock %} </div> </body> -
Module Structure Python + Django, No module named 'entities'
See the picture below for my project structure. In riskgame/view.py I tried to reach the entity Risk.py: from entities.Risk import Risk def index(request): game = Risk() return HttpResponse("test") When I tried this I get the error: ModuleNotFoundError: No module named 'entities' " Also from api.risk.riskgame.entities.Risk import Risk I get the error ModuleNotFoundError: No module named 'api' What is a good structure for my project? -
Issue in serving Static files in Django with Nginx
I am new to Django and I have referred to all other questions regarding this but being a newbie I would like to know If I am missing something else. My App Setting : STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I run the command : python manage.py collectstatic My Nginx Config file : upstream mtl_website_server { server unix:/home/ubuntu/environments/mtl_app_env/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name <My-IP>; client_max_body_size 4G; access_log /home/ubuntu/logs/nginx-access.log; error_log /home/ubuntu/logs/nginx-error.log; location /static/ { alias /home/ubuntu/environments/mtl_app_env/mtl_website/staticfiles/; } location /media/ { alias /home/ubuntu/environments/mtl_app_env/mtl_website/staticfiles/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://mtl_website_server; break; } } } I have restarted nginx too after all this with command : sudo service nginx restart But with all the css and image file it gives 404 not found error. Please help me if I am missing something. -
Python read csv file and add new row and then after some test delete the row
I am using a CSV file where first tasks is to just push that file to a server, second after the first tasks make some changes in csv file which now has an object, {'file': <_io.TextIOWrapper name='timepay/tests/Prop_Delhi.csv' mode='r' encoding='UTF-8'>} response = client.post('/path/to/push/', data=files) So point is to make a change in this file object and again push the newly edited file object to the server so the server updates the new content to a database. (In short, create a new file object with newly updated contents.) Once the newly updated file object tasks are done, remove the updated row from the file object and keep the original file as it is. -
Django makemessages "struct.error: unpack requires a buffer of 4 bytes"
I have a django instance packed in Docker container in docker-compose. I'm trying to generate makemessages files for project, but when I try to run makemessages, that's what I receieve in response root@6fc510c9c5d1:/code# python manage.py makemessages /usr/local/lib/python3.6/dist-packages/daphne/server.py:12: UserWarning: Something has already installed a non-asyncio Twisted reactor. Attempting to uninstall it; you can fix this warning by importing daphne.server early in your codebase or finding the package that imports Twisted and importing it later on. UserWarning, Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/usr/local/lib/python3.6/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/usr/local/lib/python3.6/dist-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/models.py", line 94, in <module> class Group(models.Model): File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 152, in __new__ new_class.add_to_class(obj_name, obj) File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 315, in add_to_class value.contribute_to_class(cls, name) β¦ -
pipenv: get path of virtual enviremtnt in pipenv
How to can get the path of virtualenv in pipenv? can configure it to use a custom path for newly created virtualenv? -
Django Test - Send Array of Arrays containing Integer
currently i am trying to send an array of arrays containing integers to my rest api, this is part of my test: res = self.client.post( '/data', { 'data': [ [1,2,3], [4,5,6] ] } ) In my serializer i try to print the data: def create(self, validated_data): print(self.context['request'].data) print(self.context['request'].data['data']) But i just get: <QueryDict: {'data': ['[1, 2, 3]', '[4, 5, 6]']}> [4, 5, 6] Expected: {'data': [[1, 2, 3], [4, 5, 6]]} [[1, 2, 3], [4, 5, 6]] How can this be? Did i send the wrong format or did i access the json the wrong way...? Thanks and Greetings! -
How to add Email verification in Django Rest- Framework?
I add Email verification or Email sending option in Django but in Rest framework when i try sending email from serializer class it doesn't respond. Anybody give me some idea's how can i do this ? -
Django download static file using html button
I am creating a site with Django where users can gather data from diffrent websites, review it, save it to database and download all the data as a file(txt or csv). I have this problem where i can't create a href link ({% static 'files/filename' %}) to specific static file that users can download. When i try to add href attribute to a link and click it i get this error where instead of for example this: <a id="download" href="/static/file/Shrek_reviews.txt" download=""></a> i get this: <a id="download" href="/static/file/%22%20%2B%20btn_n%20%2B%20%22_reviews.txt" download=""></a> can someone tell how can i parse file name to {% static 'file/file_name' %} so it can work propertly ? Below is my view function and ajax function that creates href attribute and download file. Thanks in advance for Your help ajax function $('button').click(function(){ var btn_t = $(this).text(); var btn_n = $(this).attr('name'); $.ajax({ type: "POST", url: "{% url 'proces:films_data' %}", data: { csrfmiddlewaretoken: '{{ csrf_token }}', btn_text:btn_t, btn_name:btn_n, }, success: function(data){ if(btn_t == 'txt') { $("#download").attr("href", "{% static 'file/" + btn_n + "_reviews.txt' %}"); } else { $("#download").attr("href", "{% static 'file/" + btn_n + "_reviews.csv' %}"); } $('#download').trigger('click'); } }); }); View function def films_data(request): db_film_data = Films.objects.all() if request.method == "POST": β¦ -
Integrity error with django-vote (new row for relation violates check constraint num_vote_up_check)
I'm trying and failing to get django-vote to work for my django app. Once a vote is made, nothing can be changed else a sql error. Also once adding a vote, this does not update the counts of the model. It seems the app is not working, as I can't find any more information on what I'm doing wrong. Here's my setup: #products.models.py from vote.models import VoteModel from django.db import models class tags(VoteModel, models.Model): name = models.CharField(max_length=50, unique=True) class gymproduct(models.Model): tags = models.ManyToManyField(tags, blank=True) .... I want users to vote on specific tags for a gymproduct. I can add a tag no problem. But when I try to use the api for the django-vote things don't seem to work as advertised. For example: #debugsqlshell from products.models import * from profiles.models import Profile #my custom user model firsttag = tags.objects.first() user = Profile.objects.first() firsttag.votes.up(user.id) #This returns true. firsttag.vote_score #This should return one, but returns 0, did the previous vote not count? firsttag.num_vote_up #This should return one, but returns 0??? firsttag.votes.down(user.id) # This breaks sql with the error: # IntegrityError: new row for relation "products_tags" violates check # constraint "products_tags_num_vote_down_check" I don't know why I get this IntegrityError error (I'm using postgres). β¦ -
Why in Saleor checkout, shipment in France and other countries not working?
I have installed Saleor on macos High sierra for evaluation purpose I have populated Saleor with Example Data, and everything works fine. But when I Try to checkout the process is stuck at shipping step, with the following message : Unfortunately we do not ship to your selected country. Please enter an alternative shipping address or contact us, if you think that's a mistake. I have try many countries but the result is the same ... All countries are configured correctly by the Example Data Any idea ? Does I miss something ? Thanks for help. -
XlsxWriter/OpenPyXl object save as HttpResponse to create download
I've been scratching my head far too long with this one. Here it goes - I am trying to export a user model class(as excel sheet), after making some changes to it then returning it as HttpResponse object for download. Here is my view code: if request.method == 'POST': form = ExportStudentscsv(request.POST) if form.is_valid(): data = form.cleaned_data #get course from dropdown value course = data.get('course') # find course id based on course title courseid = Course.objects.get(title=course) #find groups using course id groups = Groups.objects.filter(course=courseid) desiredintake = data.get('desiredintake') intakeyear = data.get('intakeyear') user_resource = UserResource() queryset = User.objects.filter(desiredintake=desiredintake, intakeyear=intakeyear, role=4) if not queryset: return page_not_found(request, "Bad Request") dataset = user_resource.export(queryset) dataset.xls response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="students.xls"' workbook = xlsxwriter.Workbook(response, {'in_memory': True}) worksheet = workbook.add_worksheet('Groups') worksheet.data_validation('B11', {'validate': 'list', 'source': ['open', 'high', 'close']}) workbook.close() response['content_type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' response['Content-Disposition'] = 'attachment; filename=students.xls' return response else: args = {'form': form} return render(request, 'epitaadmin/export_studentscsv.html', args) I followed the approach given in the third answer given in this post XlsxWriter object save as http response to create download in Django, but no luck. I don't get the data-validation changes made here - workbook = xlsxwriter.Workbook(response, {'in_memory': True}) worksheet = workbook.add_worksheet('Groups') worksheet.data_validation('B11', {'validate': 'list', 'source': ['open', β¦ -
Add a field value outside form in Django
Whenever I have to add a value to the instance of a form obtained from the context or from the URL I do it in the following way, using form.instance. class PreguntaForm(forms.ModelForm): class Meta: model = Pregunta fields = ('etiqueta', 'grupo', 'tipo_pregunta', 'opciones', 'mostrar_tabla', 'activo') def __init__(self, *args, **kwargs): cuestionario = kwargs.pop('cuestionario', False) super(PreguntaForm, self).__init__(*args, **kwargs) self.fields['grupo'].queryset = Grupo.objects.filter(cuestionario=cuestionario) class PreguntaNueva(InfoPregunta, CreateView): form_class = PreguntaForm encabezado = 'Nueva Pregunta' model = Pregunta def get_form_kwargs(self): kwargs = super(PreguntaNueva, self).get_form_kwargs() kwargs['cuestionario'] = self.dame_cuestionario() return kwargs def form_valid(self, form): form.instance.cuestionario = self.dame_cuestionario() return super(PreguntaNueva, self).form_valid(form) The problem that arises now is that I want to perform a check CreateView and EditView. To DRY, I want to do it in the clean method of the model, but the value that I assign to form.instance.cuestionario, is not available within the clean method. How could I do it? This value must not be edited by the user in any case. -
Django queryset: check for foreignkey values and substract them from queryset
Let's imagine we have 2 models: class Blog(models.Model): title = models.CharField(...) status = models.Charfield(choices=choices.STATUS, default='pending') class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name="entries") text = models.TextField() ready = models.BooleanField(default=False) Every entry can be added in many blogs. I want to filter all entries with ready = True whose blog has the status = published. -
get request on empty lists return 200 status code
I have this view: def get(self,request): cities = City.objects.filter(State__in=request.GET.getlist('state_id')) serializer = citySerializers(cities,many=True) return Response({"message": "data loaded!", "data": serializer.data}) If I enter a state_id that does not exist on the database it returns me status code 200,I expect it returns 404 for an empty list. What I did wrong? -
View function is not being called after submitting form in django
I have made a simple form inside a html file whose path is www.site.com/posts/5. Whenever the form is submitted, it redirects back to the same page i.e www.site.com/posts/5 displaying a message given by user in the form. However, whenever the form is submitted it doesn't call the foobar view. The urls.py, views.py and html files are as follows:- urls.py urlpatterns = [ path('posts/<int:foo>',user_views.display, name="display", path('posts/<int:foo>',user_views.foobar, name="makefoo"), ] views.py def foobar(request, foo): #do something html file <form name="fooform" action= "{% url 'makefoo' 5 %}" method = "post"> {% csrf_token %} <input type="text" name="FOO_BODY" maxlength="300" required> <input type="submit" value="comment"> <input type="reset" value="clear"> </form> -
Is it bad practice to store a Pandas DataFrame as a PickledObjectField in a Django Model?
I am storing a Pandas DataFrame in a Django model as a PickledObjectField. I need to access and modify this DataFrame based on certain logic. Pandas makes this job a lot easier, where I have an engine class that uses Pandas selects and filters. Should I have a separate model where I store each row in the DataFrame, then read this using django-pandas, perform the manipulation and update the model? The key here is that the DataFrame will be modified by adding/removing some rows, so if it is to be stored in a model, it would be easier to drop all records and re-populate the model. The DataFrame is less than 100 rows, so I'm not worried about scalability. -
How to access my ChoiceField in views.py?
How do I access the ChoiceField options in views.py so I can print different outputs based on it? (I tried the code below but it doesn't seem to work, I don't know where went wrong) forms.py class BeamForm(forms.Form): CHOICES = (('Add on', 'Add on'),('Reset', 'Reset'),) field = forms.ChoiceField(choices=CHOICES) views.py from . import forms if forms.BeamForm.field == 'Add on': print("Option is add on") elif forms.BeamForm.field == 'Reset' print("Option is Reset") else: print("nothing") -
Using session.set_expiry() in custom AuthenticationForm in Django.
I am trying to set remember me in login and use LoginView as view. Is it possible to set session.set_expiry(0) in the custom AuthenticationForm? class CustomAuthenticationForm(AuthenticationForm): username = forms.CharField(); password = forms.CharField(), remember_me = forms.BooleanField(widget=forms.CheckboxInput(), label='Remember me') def clean_remember_me(self): if not self.cleaned_data['remember_me']: set expiry immediately <-- here SESSION_EXPIRE_AT_BROWSER_CLOSE might be usable but can I use session.get_expiry(0) in this case? How can I do without writing a custom view? -
Django converting tiff to jpeg with pillow
I'm working with Django in Python 3, and I have a model with an ImageField and I'm trying to override the .save() to do tiff to jpeg conversion: from PIL import Image from io import BytesIO from django.core.files.base import ContentFile class MyModel(models.Model): image = models.ImageField(upload_to=upload_image_to, editable=True, null=True, blank=True) def save(self, *args, **kwargs): pil_image_obj = Image.open(self.image) new_image_io = BytesIO() rgb_pil_image_obj = pil_image_obj.convert("RGB") rgb_pil_image_obj.save(new_image_io, quality=90, format='JPEG') # temp_name = self.image.name # self.image.delete(save=False) # self.image.save( # temp_name, # content=ContentFile(new_image_io.getvalue()), # save=False # ) super().save(*args, **kwargs) However, this leads to: tempfile.tif: Cannot read TIFF header. *** OSError: -2 If I try the save experiment but only opening the TIFF file from disk instead of feeding PIL.Image with the Django InMemoryUploadedFile, then everything works absolutely fine and the tiff is converted to a jpeg. Also pil_image_obj.verify() doesn't throw any exceptions. I'm using Pillow==5.3.0