Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'id' expected a number but got 'filter_data'. DJANGO, AJAX
I am working on filters in my project. Based on the tutorial, I started adding Ajax so that I could filter cards by several categories. Everything was working fine until I added the data and jsonResponse. Now every time I click the checkbox I get this error Ajax $(document).ready(function(){ $(".axaLoader").hide() $(".filter-checkbox").on('click', function(){ var _filterObj={}; $(".filter-checkbox").each(function(index,ele){ var _filterVal=$(this). val(); var _filterKey=$(this). data('filter'); _filterObj[_filterKey]=Array.from(document.querySelectorAll('input[data-filter='+_filterKey+']:checked')).map(function(el){ return el.value; }); }); $.ajax({ url:'filter_data', data:_filterObj, dataType:'json', beforeSend:function(){ $(".ajaxLoader").show(); }, success:function(res){ console.log(res); $("#filteredProducts").html(res.data); $(".ajaxLoader").hide(); } }); }); }); views.py def filter_data(request): return JsonResponse({'data':'hello'}) urls.py from django.urls import path, include from django.contrib.auth.views import PasswordChangeView from . import views from .forms import PasswordUpdateForm urlpatterns = [ path('', views.store, name="store"), path('cart/', views.cart, name="cart"), path('checkout/', views.checkout, name="checkout"), path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('registration/', views.registrationPage, name="registration"), path('profile/', views.profile, name="profile"), path('change_password/', PasswordChangeView.as_view(template_name='store/change_password.html', success_url='profile', form_class=PasswordUpdateForm ), name="change_password"), path('change_password/profile/', views.profile, name="profile"), path('update_item/', views.updateItem, name="update_item"), path('update_wish_item/', views.updateWishItem, name="update_wish_item"), path('process_order/', views.processOrder, name="process_order"), path('<str:id>', views.product_view, name="product_view"), path('wishlist/', views.wishlist, name="wishlist"), path('search/', views.search, name="search"), path('filter_data/', views.filter_data, name="filter_data"), path('search/<str:id>',views.product_view, name="product_view"), ] Error Traceback (most recent call last): File "C:\Users\Admin\PythonProject 555\venv\lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "C:\Users\Admin\PythonProject 555\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Admin\PythonProject 555\boots\store\views.py", line 118, in product_view product = Product.objects.filter(id=id).first() File … -
Failed to save Django formset with queryset
i have faced the problem in django formset, i want to update formset using function view, when this line formset = MyFormset(request.GET or None, instance=form_main, queryset=queryset) included cant save but if i remove instance=form_main, queryset=queryset) it does not populate data but i can add manually and save it. I want this formset to polulate from database and to save it back to database view.py form_main = get_object_or_404(MyModel, pk = pk) queryset = MyFormset.objects.order_by('item') if request.method == 'GET': form = MainForm(request.GET or None, instance=form_lpo) formset = MyFormsetForm(request.GET or None, instance=form_main, queryset=queryset) elif request.method == 'POST': formset = Grn_LineItemFormset(request.POST) form = MainForm(request.POST) if form.is_valid(): newmodel= NewModel.objects.create(................) -
Need to add custom forms based on User input
So basically I need to implement the following functionality In my django project, the admin should be able to select number of fields he needs and their type(textfield, radio buttons, etc.., mandatory fields and non mandatory fields ) for his form and based on this a new page with a form which has the aforementioned fields should be rendered. The admin should be able to add this as a backend script in django model. I tried a way out via Model forms but couldn't get a clear layout as to how should i use it. I am fairly new to this techstack. Any guidance would be helpful Thanks -
Django metadata returns blank?
I want to apply some metadata to a stripe-checkout. No errors. When the payment is done without errors, I am not able to collect the metadata again. The returned data is just blank like this {}. The checkOutSission-view looks like this: @csrf_exempt def createCheckoutSession(request): if request.method == 'POST': data = json.loads(request.body) product = data[0] option_back = data[1] option_legs = data[2] option_length = data[3] # Create a Stripe Checkout session session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ 'price_data': { 'currency': 'eur', 'product_data': { 'name': product, 'description': (f'Back: {option_back} | Legs: {option_legs} | Length: {option_length}'), 'quantity': 1, 'metadata': { 'option_back': option_back, 'option_legs': option_legs, 'option_length': option_length, }, }, 'unit_amount': 300, # in euro }, }], mode='payment', success_url='http://127.0.0.1:8000/configurator/success/?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://127.0.0.1:8000/configurator/cancel/', ) return JsonResponse({'session_id': session.id, 'checkout_url': session.url}) else: return JsonResponse({'error': 'Invalid request method'}) The view that schould be called after the payement looks like this: def success(request): session_id = request.GET.get('session_id') session = stripe.checkout.Session.retrieve(session_id) items = session.get('customer_details') print(items.email) values = session.get('metadata') print(values) # Gjør noe med produktinformasjonen return HttpResponse("Success") Why do it not work like my predictions? I have tried to move the "metadata-block" in diffrent levels of the session-data-blocks. Nothing makes the wanted results. -
Django - Can't fetch Json data in javascript
Hello I am pretty new to Django and Javascript I want to build a simple application where users can write posts and see a list of all posts in reverse chronologial order on the index page. (The index page is rendered fine.) I created some Posts via the admin interface. Unfortunately I can't figure out why I am not able to fetch the JsonResponse and no div gets append to my template. the code looks as following: first I've created a Posts model class Posts(models.Model): text = models.TextField(max_length=512) timestamp = models.DateTimeField(auto_now=True) def serialize(self): return { "id": self.id, "text": self.text, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), } My view function to get all posts from the datatbase is called via path("get_posts", views.get_posts, name="get_posts"), and looks like this: @login_required def get_posts(): # get all posts posts = Posts.objects.all() # Return posts in reverse chronologial order posts = posts.order_by("-timestamp").all() return JsonResponse([post.serialize() for post in posts], safe=False) In my Javascript file (index.js) I want to load all Posts, create a div for each post and append them to my template document.addEventListener('DOMContentLoaded', function() { // By default, load_posts load_posts(); }); function load_posts() { // get posts from /posts API Route fetch('/get_posts') .then(response => response.json()) .then(posts … -
django.contrib.auth import get_user_model
I get an error in my User AttributeError: type object 'User' has no attribute 'objetcs' I get the error in forms.py when I try to use my User. // forms.py // from django import forms from django.contrib.auth import get_user_model from django.db import models from . import models User = get_user_model() class PerfilForm(forms.ModelForm): class Meta: model = models.Perfil fields = '__all__' exclude = ('usuario',) class UserForm(forms.ModelForm): password = forms.CharField( required=False, widget= forms.PasswordInput(), label='Senha' ) password2 = forms.CharField( required=False, widget= forms.PasswordInput(), label='Confirmar senha' ) def __init__(self, usuario=None, *args, **kwargs): super().__init__(*args, **kwargs) self.usuario = usuario class Meta: model = User fields = ('first_name', 'last_name', 'username', 'password', 'password2', 'email',) usuario_db = User.objetcs.filter(username=usuario_data).first() **<-- here I get the error** email_db = User.objetcs.filter(email=email_data).first() -
Django rest framework- blog post comment delete permission for admin user and owner user
does anyone know how to set delete permisssion for commented owner to delete the comment and for the admin user, delete all comments Serializers.py class DeleteCommentSerializer(serializers.ModelSerializer): class Meta: model = CommentModel fields = '__all__' Views.py class CommentDeleteView(generics.DestroyAPIView): permission_classes = [IsAdminUser,IsOwner] queryset = CommentModel.objects.all() serializer_class = DeleteCommentSerializer def perform_delete(self, serializer): serializer.save(user=self.request.user) Permissions.py class IsOwner(BasePermission): def has_permission(self, request, view): if request.method in ['PUT','DELETE']: return True return False def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.user == request.user -
How do I write a Django query that searches a nested JSON array?
I have the following JSON object (named 'data') on my Draft model: DRAFT1 data= { communications = [ {name: "john"}, {name: "bobby"} ] } DRAFT2 data= { communications = [ {name: "mark"}, {name: "erin"} ] } I'm guessing this is vaguely correct for a query, but I can't figure out the syntax for the '*'? Draft.objects.filter(data__communications__*__name__in=['john', 'erin']).count() How can I write a Django/Postgres query to return DRAFT1 and DRAFT2 as the result? -
AWS lightsail deployment Errors django
Good day, I have built a python / django webapp that i'm ready to deploy. I'm trying to deploy my webapp using AWS Lightsail, but the problem i'm facing is that my webapp will not load. I'm receving the error as follows:, but on my local Visual Studio code, but webapp is working just fine. What am i missing? My settings code is -
Point custom domain to a different website Django
I have a Django project deployed to a ubuntu server from digital ocean, using Apache as the web server and mod_wsgi, a custom domain name from Namecheap, and an SSL certificate. It has everything needed to be a solid website. But I also have a flask app deployed on an EC2 instance from AWS, besides changing the name servers on NameCheap to point to my EC2 instance, what else should I do for my domain to point to my Flask app instead of my Django app? Is it just as simple as removing the domain name from ALLOWED_HOST in Django settings.py? or is this more complex now that I have an SSL certificate? I hope it's not a meaningless question. -
How can I filter the queryset to only display the just created assignment
I have a model form which creates assignments, and each assignment needs to have some criteria, and so the next page in the creation process is a model formset which lets the user create multiple criteria at once. The problem I'm currently having is that I only want the user to add criteria to the assignment that they have just created, rather than using the dropdown menu and selecting the assignment manually. I've read about modifying the queryset and it seems like the way to go but I',m not sure how I can get the value of just the newly created assignment. The models: # Assignment class Assignment(models.Model): assignmentName = models.CharField(max_length=100) def __str__(self): return self.assignmentName def get_absolute_url(self): return reverse('assignment-view') #Criteria class Criteria(models.Model): assignmentID = models.ForeignKey(Assignment, on_delete=models.CASCADE) criteriaDescription = models.TextField() def __str__(self): return self.criteriaDescription View: criteriaFormset= modelformset_factory(Criteria, fields=('assignmentID','criteriaDescription')) form = criteriaFormset() return render(request,'markingApp/createCriteria.html', {'form': form}) -
TOKEN_LIMIT_PER_USER in django rest knox is not working
Everything was working fine until I created a custom user for my django project and since then, time limit per user is no longer working but the expiry date for the token is working fine, I have been searching online to find any solution but I can find any so I'm stack and don't know how to go about it to fix it so I flush my database and do the makegrations and migrate again but none of them worked -
How to add clipboard module to QuillField() in django for using in django admin?
Copying and pasting are not handling correctly on the Quill Editor. Is there any additional instructions which are needed when using the QuillField() in django to properly enable it, specially for copying text documents with images? This is how I am doing it: class Post(models.Model): customer = models.ForeignKey(Customer,on_delete=models.DO_NOTHING,related_name='post_customer') title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.DO_NOTHING,related_name='posts_author') updated_on = models.DateTimeField(auto_now= True) created_on = models.DateTimeField(auto_now_add=True) asset = models.IntegerField(choices=POST_ASSET, default=0) status = models.IntegerField(choices=POST_STATUS, default=0) article = QuillField(blank=True, null=True) -
How would I perform post-setup init steps in Django?
Where would I put steps I'd like to perform AFTER Django's setup() call? I expected this would already be a Django signal (like post_migrate). It seems like making my own versions of get_wsgi_application, etc. with callbacks is the next best option. Since that code is rarely touched I can imagine that it could fail silently and no one would know why. For a little background, I'm making my own task runner on lambda using Django on Postgres. Being able to dynamically define scheduled python functions with their own arguments is a key feature. At start up, I need to connect database entries for functions and their definitions in code. The way I get around this problem today is at the image entrypoint: if not python_function_registry.is_registry_initialized(): python_function_registry.registry_setup() There are several places I do this today. It seems like there are several potential benefits to a post_setup signal (or something similar), so I expect it must already exist? Thanks for your help! -
why the @property django decorator doesn't work
I need to pass the 'def get_sale' method to the model in views to sort the products by get_sale, but after passing it an error comes out models.py @property def get_sale(self): '''Расчитать стоимость со скидкой''' price = int(self.price * (100 - self.sale) / 100) return price views.py class SortItems(GoodsHome):#сортировка товара def get_queryset(self): sort_types = { '0': '-time_create', '1': 'time_create', '2': 'get_sale', '3': '-get_sale', } sort_type = sort_types[self.kwargs['sort_type']] if 'query' in self.kwargs: query = self.kwargs['query'] return super(SortItems, self).get_queryset().filter(Q(artist__icontains=query) | Q(album__icontains=query)).order_by(sort_type) return super(SortItems, self).get_queryset().order_by(sort_type) -
Django Rest Framework Serializer giving error for Foriegn key field can not be null
I am working on a restframework api using DRF but while executing perform create its showing error for a foriegn key field "can not null" Serializer : `class StyleEditProductSerializer(ModelSerializer): class Meta: model = StyleEditProduct fields = '__all__' read_only_fields = ('style_edit',)` Model : `class StyleEditProduct(BlankModel): product = fields.default_fk_field(Product, related_name='style_edits') sort_order = models.IntegerField(default=0) style_edit = fields.default_fk_field(StyleEdit) class Meta: unique_together = ('product', 'style_edit')` Views : `class StyleEditProductMultipleView(CreateAPIView): serializer_class = StyleEditProductSerializer def create(self, request, *args, **kwargs): style_edit = get_object_or_404(StyleEdit, id=self.kwargs.get('style_edit_id')) style_edit_products = [] for product in request.data['data']: product['style_edit_id'] = style_edit.id style_edit_products.append(product) print(style_edit_products) serializer = self.get_serializer(data=style_edit_products, many=True) serializer.is_valid(raise_exception=True) try: self.perform_create(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) except Exception as e: print(e) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)` Error : [{'sort_order': 1, 'product': 1, 'style_edit_id': 2}] (1048, "Column 'style_edit_id' cannot be null") I am not able to understand I am passing the data for the style_edit_id in the serializer but still giving the error, Can anyone help me in this I have tried to check in model and in serializer but I am facing this issue and I can't understand why its giving error -
Django admin restrict max inline forms by parent field
I have the following two models in Django. Model Contest has questions and Questions is another django model: class Contest(models.Model): min_questions = models.IntegerField() class Question(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name="questions") question = ... Then I add the questions as an inline in the contest admin: class QuestionInlineForm(forms.ModelForm): class Meta: model = Question fields = \['question'\] class QuestionInline(NestedStackedInline): model = Question form = QuestionInlineForm extra = 1 inlines = \[AlternativeInline\] #Igonre this class CustomContestAdmin(NestedModelAdmin): inlines = \[QuestionInline,\] This let me create the questions inside the contests form, the problem is that I want to restrict the number of questions to create using the field min_questions of the Contest model, so that the form doesn't let me create a contest if the total amount of questions is less than the field min_questions. Is there a way to achieve this? I'm using the nested_admin library and I tried the method clean but the questions count shows as 0 because the questions have to be added after the instance of contest is created. I think this could be done by using transactions so I can create the Contest, then add the questions and before saving to the database check if the questions count is … -
Dynamic background change depending on the incoming link
I'm currently writing a site in django and I want to create a dynamic link page where the background depends on what comes from the link. I know I can make templates for each background, but I have over 500 of them, so this method seems inappropriate. Is there a better way to do it? I tried join static and dinamic paths and also send prepared path from backend but this both and some other way were unsuccessful at least in my code -
Microsoft Azure Face API gives APIErrorException: (InvalidRequest) Invalid request has been sent
enter image description here face ID is None Calling Face ID Generation Catching Update Function image URL is /media/missingpersons/IMG_20220827_191210.jpg image Path is C:\Users\Dell\Desktop\FYP\media\missingpersons\IMG_20220827_191210.jpg face ID is None Calling Face ID Generation Internal Server Error: /people/verify-missing-person/1 Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Dell\Desktop\FYP\people\views.py", line 120, in post response_detected_face=generate_face_id(self.object.photo.path) File "C:\Users\Dell\Desktop\FYP\people\views.py", line 78, in generate_face_id response_detected_face = face_client.face.detect_with_stream( File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\azure\cognitiveservices\vision\face\operations\_face_operations.py", line 783, in detect_with_stream raise models.APIErrorException(self._deserialize, response) azure.cognitiveservices.vision.face.models._models_py3.APIErrorException: (InvalidRequest) Invalid request has been sent. [21/Mar/2023 20:58:45,600] - Broken pipe from ('127.0.0.1', 58067) Internal Server Error: /people/verify-missing-person/1 Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Dell\Desktop\FYP\people\views.py", line 120, in post response_detected_face=generate_face_id(self.object.photo.path) File "C:\Users\Dell\Desktop\FYP\people\views.py", line 78, … -
How to write a chatting app (dating app to be specific) in Python?
I'm trying to figure out how to get started with this because I'm not that good when it comes to programming, I did some projects in Flask but I don't know other frameworks. What I'm doing is a dating app where you create a profile and can message other users. I want the chat to be offline - to look like e-mails basically. I searched for some chatting app projects on GitHub, but the ones that met my needs weren't up to date (especially Django) and it was hard for me to try to change them. What framework would be the best choice here? Django seems like a good fit but like I said, I haven't coded in it. Is it possible to do it in Flask without it being too complicated? Do you have some examples that actually work without having to change the code? If you have any tips feel free to comment! -
Save selection from dropdown menu and display on a redirected page?
I am very new to django. I have a login page which allows you to select either Student, Admin, Instructor. How do I save the value selected and display it on the next page after you press Login? This is what I have so far. I believe my url routings are incorrect which is causing some sort of problem. Here is my file structure: Project file structure. This is what I have so far. In my login.html, I have a drop down menu where it classifies the selction as user_type. {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Log In</h2> <form method="post"> {% csrf_token %} <label for="user_type">User Type:</label> <select name="user_type" id="user_type"> <option value="admin">Administrator</option> <option value="instructor">Instructor</option> <option value="student">Student</option> </select> {{ form.as_p }} <button type="submit">Log In</button> </form> <br> <a href="#">Forgot Password?</a> {% endblock %} From there, I need to get the value using a function in views.py. So I wrote this: ef login_view(request): if request.method == 'POST': user_type = request.POST.get('user_type') request.session['user_type'] = user_type return redirect('home') else: return render(request, 'login.html') I believe I also need to retrieve the value so I made another function in views.py def home_view(request): user_type = request.session.get('user_type') return render(request, 'home.html', {'user_type': user_type}) Then … -
set-cookie on http://localhost won't set
I have a react (next.js) project with django+graphql backend. Is it possible to set session cookie while having frontend hosted on http://localhost:5000? I tried setting django variables for httpOnly and secure and I see cookie coming from backend, however it won't set no matter what. Example of response headers: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://localhost:5000 Content-Length: 168 Content-Type: application/json Date: Tue, 21 Mar 2023 15:29:38 GMT Server: WSGIServer/0.2 CPython/3.7.16 Set-Cookie: csrftoken=myCsrfCookie; expires=Tue, 19 Mar 2024 15:29:38 GMT; Max-Age=31449600; Path=/; SameSite=None Set-Cookie: sessionid=mySessionIdCookie; expires=Tue, 04 Apr 2023 15:29:38 GMT; Max-Age=1209600; Path=/; SameSite=None Vary: Cookie X-Frame-Options: SAMEORIGIN -
How to use miniconda as a linux system user
I'd like to run a Django app on a linux machine using miniconda as a tool for managing packages and virtual environment. Systemctl will launch gunicorn as a dedicated system user, say my_app_user. Sources will be on /opt/my_app with permission only for my_app_user. What is the correct / secured way to install miniconda for such use case ? -
Documentation build issues during upgrade netbox
I am upgrading my netbox from 2.11.12 to 3.3.10. PYTHON=/usr/local/bin/python3.9 ./upgrade.sh At this time, a 'utilities' module error occurs in 'mkdocstrings', and I would appreciate it if you could tell me how to solve it. Successfully installed aniso8601-9.0.1 arrow-1.1.1 cython-0.29.33 graphene-3.2.2 graphene-django-3.0.0 graphql-core-3.1.7 graphql-relay-3.1.5 graphql-scalars-0.2.4 griffe-0.25.5 mkdocstrings-python-0.8.3 Skipping local dependencies (local_requirements.txt not found) Applying database migrations (python3 netbox/manage.py migrate)... Operations to perform: Apply all migrations: admin, auth, circuits, contenttypes, dcim, django_rq, extras, ipam, sessions, social_django, taggit, tenancy, users, virtualization, wireless Running migrations: No migrations to apply. Checking for missing cable paths (python3 netbox/manage.py trace_paths --no-input)... Found no missing console port paths; skipping Found no missing console server port paths; skipping Found no missing interface paths; skipping Found no missing power feed paths; skipping Found no missing power outlet paths; skipping Found no missing power port paths; skipping Finished. Building documentation (mkdocs build)... INFO - Cleaning site directory INFO - Building documentation to directory: /opt/netbox-3.3.10/netbox/project-static/docs INFO - The following pages exist in the docs directory, but are not included in the "nav" configuration: - index.md ERROR - mkdocstrings: No module named 'utilities' ERROR - Error reading page 'plugins/development/forms.md': ERROR - Could not collect 'utilities.forms.ColorField' I tried installing various packages/modules with pip, … -
Django form field uploading error bad filename
In that code I try to get the first page to make preview image. def form_valid(self, form): text_book = form.save(commit=False) text_book.owner_id = self.request.user.pk # i'm trying to get the first page to make preview image my_file = self.request.FILES['book_file'].file pdf_file = fitz.open(my_file) page = pdf_file.load_page(0) pix = page.get_pixmap() preview_image = Image.frombytes('RGB', [pix.width, pix.height], pix.samples) preview_image.thumbnail((200, 200)) image_io = BytesIO() preview_image.save(image_io, format='JPEG') image_data = image_io.getvalue() content_file = ContentFile(image_data) text_book.preview_image.save(f'text_book_preview_image{Path(text_book.book_file.name).stem}_preview.jpg', content_file, save=False) text_book.save() return HttpResponseRedirect(self.success_url) Everything works. But when I put that in settings: DATA_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 * 500 FILE_UPLOAD_MAX_MEMORY_SIZE = DATA_UPLOAD_MAX_MEMORY_SIZE I get "bad filename". When code works without MAX_MEMORY_SIZE settings, my_file is <tempfile._TemporaryFileWrapper object at 0x7f6491f1ae20> But when I put that settings my_file is <_io.BytesIO object at 0x7f69b6945950> What is wrong?