Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset of related records, but only the max from the related table
Lets say I have two django models which are related. Groups, and People, who belong to a single group. class Group(models.Model): name = models.CharField(max_length=100, null=True, blank=True) class Person(models.Model): group = models.ForeignKey('Group', on_delete=models.CASCADE, related_name='group') name = models.CharField(max_length=100, null=True, blank=True) birthdate = models.DateTimeField(auto_now_add=True) What I would like to do, is return a queryset of the Person objects, which is composed of only those people with the greatest birthdate for each group. So if there are 5 'Groups' I want a queryset of 5 'Person' objects, determined by maxmium birthdate. -
Can a parent class check if child class has such field?
I know that we can reference the parent's model from a child but is there a way to have it the other way? sorry for any typo here. Let's say if parent is class Parent(models): has_this = models.Charfield(max_length=128) class Child(parent): has_that = models.Boolean(default=True) ch = Child.objects.filter(id=1).first() // this will be instance of both Parent and Child as expected pa = Parent.objects.filter(id=1).first() // is actually return the same as above but does not has the `Child` field `has_that` What my question is, is there a way for pa to differential from a regular Parent if a query is called using Parent.objects.filter I tried using isisntance but for pa, it's only true if it's Parent for ch it's true for both. I cannot think of another way to differential this. Also, Parent will not be abstract. P.S. I thought of using hasattr but this would not work too. Thanks in advance. -
django Jquery, Ajax request
Is there any way to request something with post method with out using web form? The next example works fine but not if I use post method, is that because I'm not using web form ? <script type="text/javascript"> $(function(){ $.ajax({ url: 'http://127.0.0.1:8000/ajax_test/', type: 'get', success: function(data) { alert(data) }, failure: function(data) { alert('Got an error dude'); } }); }); Regards -
How can I write this Group By query with Django ORM?
I'm trying to convert this SQL into ORM Django: SELECT * FROM DOCUMENTO D WHERE D.PASTA_ID = 4 AND D.PAI_ID = 10 AND D.VERSAO = (SELECT MAX(VERSAO) FROM DOCUMENTO E WHERE D.ID_DOC = E.ID_DOC GROUP BY ID_DOC) I've tried to use annotate but doesn't work. Someone can help me? models class Documento(models.Model): pasta = models.ForeignKey(u'Pasta') pai = models.ForeignKey(u'self', null=True, blank=True, on_delete=models.SET_NULL, related_name='doc_pai') nome = models.CharField(u'Nome', max_length=255) versao = models.IntegerField(u'Versao', default=1) id_doc = models.IntegerField(u'ID Documento', null=True) -
Change the Category of an item in Django
I am trying to change the category of an item to another category in Django. Whenever, you click on a Category, it shows the lists belongs to it. It is my HTML <ul> {% for todo in todolist.todos.all %} {% if not todo.is_finished %} <li><input type="checkbox" id="checkbox" data-todo-id="{{ todo.id }}"> {{ todo.description }}<p>{{ todo.summary }}{{todolist.id}}</p></li> <form action="{% url 'lists:migrate_todo' todo_Cat=todolistCat.id %}" method=post> <select>{% for todolistCat in user.todolists.all %}<option>{{todolistCat.title}}{{todolistCat.id}}</option>{% endfor %}</select> {% csrf_token %} <button><input id="submit" type="button" value="Click" /></button> </form> {% endif %} {% endfor %} </ul> Here, todo is each item list. todolist.todos.all is the list of all items. user.todolists.all is the list of all Categories and todolistCat is each Category where lists belongs to. I am using <select> method, after selecting the new category, item should be added to new Category. I am trying to call the migrate_todo() when you click on button. This is my views.py , def index(request): return render(request, 'lists/index.html', {'form': TodoForm()}) def todolist(request, todolist_id): todolist = get_object_or_404(TodoList, pk=todolist_id) if request.method == 'POST': redirect('lists:add_todo', todolist_id=todolist_id) return render( request, 'lists/todolist.html', {'todolist': todolist, 'form': TodoForm()} ) def migrate_todo(request, todo_id): instance = get_object_or_404(Todo, pk=todo_id) #do something return redirect('lists:index') migrate_todo is the function that I want to call. This is … -
django-registration seems to be shortening hashed password when using subclassed RegistrationView
I'm trying to setup django-registration form with an extra field or two. I've read the documentation and scoured StackOverflow. I'm getting a problem where the user is registered with the new fields but when I try and login it doesn't recognise the password. I've created a new view (I've just cut and pasted register from django-registration because I just want it running initially): class MyRegistrationView (RegistrationView): form_class = UserRegForm def register(self, form): new_user = RegistrationProfile.objects.create_inactive_user( form, site=get_current_site(self.request) ) signals.user_registered.send(sender=self.__class__, user=new_user, request=self.request) return new_user It uses this form: class UserRegForm(RegistrationForm): CHOICES = Institution.objects.all().order_by('name') institution=forms.ChoiceField(choices=( (x.id, x.name) for x in CHOICES ), required = True) These are the additional models: class Institution(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return u'%s' % (self.name) class UserProfile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) institution=models.ForeignKey( Institution, null=True, blank=True) def __unicode__(self): return u'%s' % (self.user) My URL url(r'^register', views.MyRegistrationView.as_view(form_class=UserRegForm), name='registration_register'), And I've added this to save the data: from models import UserProfile from forms import UserRegForm def user_created(sender, user, request, **kwargs): form = UserRegForm(request.POST) try: data = UserProfile.objects.get(user=user) except: data = UserProfile(user=user) data.institution = form.data["institution"] data.save() from registration.signals import user_registered user_registered.connect(user_created) Everything works in that the user is registered, an email is sent out, the institution is saved to the UserProfile, but … -
How to render child block value in a parent wagtail template
I have a custom defined carousel block that I'd like to render the value stored in the block on sequence_member.html. The block is defined as the following: class CarouselItemBlock(blocks.StructBlock): name = blocks.CharBlock(required=False) And here is what I've tried to render the name in sequence_member.html: {{ child.block.name }} will tell me it's carouselitem {{ child.value }} renders an html template that has all data stored in CarouselItemBlock including the name of it. So I am assuming this is 100% achievable. I'd like to display the name in the html template with something like {{ child.value.name }} That will be rendered as Testing Carousel Block. But the above returns nothing. I'm reading the docs http://docs.wagtail.io/en/v1.9/topics/streamfield.html#boundblocks-and-values but can't seem to find a good way to show it either. -
Number of online people in django
I have a website and i want to find number of online users in my website(All of users logged to their account or not): And when they get offline or close page the number of online users get update: How can i do that?is there any library to do that? -
How to concatenate QuerySets from a list of QuerySet
I come across this syntax on stackoverflow from itertools import chain result_list = list(chain(page_list, article_list, post_list)) I need to concatenate a bunch of QuerySets with something like this: prjExpList = list(chain(lvl for lvl in prjlvl)) prjEnvList = list(chain(env for env in prjEnv)) This gives me an error of AttributeError: 'QuerySet' object has no attribute '_meta' My goal is to concatenate a bunch of QuerySets that's stored inside a list prjlvl and prjEnv How do I do that? -
There is a way to call a function in ListView?
I have a ListView and I want to execute a script in python to update our database everytime I enter in the listview, or periodically. Is there a way to do that ? class AccessPointList(generic.ListView): #receives the whole set of AccessPoint and send to HTML model = AccessPoint #call a function in python -> c.update() #or create a def to update our database -
Django foreign key selection
I am making a simple Django application that records the performance of running athletes. The models for the application look like this: class Athlete(models.Model): name = models.CharField(max_length=30) nationality = models.CharField(max_length=30) class TrainingSession(models.Model): training_date = models.DateTimeField() location = models.CharField(max_length=30) athlete = models.ForeignKey(Athlete) class Run(models.Model): run_time = models.IntegerField() training = models.ForeignKey(TrainingSession) An athlete has multiple training sessions and in each of those sessions, the athlete runs multiple times (each time, his time will be recorded in seconds). I found out that I can easily make queries between these models, however, I still struggle with the following problem: I want to select the runners that CONSISTENTLY run between for example 20 and 30 seconds. When I select runners like this: athletes = Athlete.filter(trainingsession__run__run_time__range=[20,30]).distinct() I get all athletes that once ran between 20 and 30 seconds, but also athletes that once ran 35 seconds. Can you help me to solve this? Hopefully, there's a Django query that makes this easy! -
WinError 10013 tried several suggestions but could not resolve it
It has been almost a month since I got this problem, and I really appreciate your help. While trying to login in my Django Web App, i encounter OSError at /accounts/login/.I am able to login in 127.0.0.1:8000/admin, but not in the /accounts/login which produces the Error Code: OSError at /accounts/login/ [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions Request Method: POST Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 1.11.1 Exception Type: OSError Exception Value: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions Exception Location: C:\Python35-32\lib\socket.py in create_connection, line 702 Python Executable: C:\Python35-32\myvenv_python3\Scripts\python.exe Python Version: 3.5.2 Python Path: ['C:\\Users\\Kaleab\\Desktop\\ecomstore', 'C:\\Python35-32\\lib\\site-packages\\sqlalchemy-1.1.7-py3.5-win32.egg', 'C:\\Python27', 'C:\\Python35-32\\myvenv_python3\\Lib\\site-packages', 'C:\\Python35-32', 'C:\\Users\\Kaleab\\Desktop\\ecomstore', 'C:\\Python35-32\\myvenv_python3\\Scripts\\python35.zip', 'C:\\Python35-32\\DLLs', 'C:\\Python35-32\\lib', 'C:\\Python35-32\\myvenv_python3\\Scripts', 'C:\\Python35-32\\lib\\site-packages', 'C:\\Python35-32\\lib\\site-packages\\win32', 'C:\\Python35-32\\lib\\site-packages\\win32\\lib', 'C:\\Python35-32\\lib\\site-packages\\Pythonwin'] Possible Causes and Solutions Cause: Socket access needs administrative privilege. Attempted Solution: • Granted Administrator access to python.exe by navigating to the virtual environment. • Navigate to CMD.exe , right click , properties, grant administrator privilege. Cause: Port can be already used by another program. Attempted Solution: Checked the ports using TCPView windows program and see that the port 8000 is not used by another program. Cause: Socket access blocked by … -
Serialize multiple models and send all in one json response django rest framework
This question is being asked to expand and fill in the holes from this one: Return results from multiple models with Django REST Framework my goal is to return a json object that I will use to dynamically populate the options in various select statements in my html code. so I want to grab a attribute from model a, another from model b etc then I want all the values from attribute a and b and c etc to be in a json array in a json value so json ={ modelA: ['atter1, atter2, atter3] modelB: {'atter1, atter2, atter3] model..:{you get the point} } this part from the post referenced above makes sense: class TimelineViewSet(viewsets.ModelViewSet): """ API endpoint that lists all tweet/article objects in rev-chrono. """ queryset = itertools.chain(Tweet.objects.all(), Article.objects.all()) serializer_class = TimelineSerializer what doesn't is this: class TimelineSerializer(serializers.Serializer): pk = serializers.Field() title = serializers.CharField() author = serializers.RelatedField() pub_date = serializers.DateTimeField() how do I set the the seperate model attributes to the correct json key? I assume its something similar to a serializer relation but these values aren't related to eachother via onetoone, onetomany, or many to many. I just want to grab all this info at once instead of … -
Django Tutorial Templates without head, body and Doctype?
I'm just wondering, wether it is the right/recommended way to omit the Doctype, head und body tags? Because at least the Django tutorial does it, as can be seen in tutorial 3, in the polls/templates/polls/index.html: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} -
Reading CSV in Python/Django - Weird Mapping for csvDict
I am trying to read a csv file line-by-line in my views.py file. The csv file is structured as follows: xk, ab, cd 11, 20, 30 31, 27, 35 etc if request.method == "POST": pdb.set_trace() form = FormName(request.POST, request.FILES) file = request.FILES['csv'].read() if form.is_valid(): try: reader = csv.DictReader(file) for row in reader: xk = row['xk'] Before executing the last line above, when I print 'row' in pdb, I get {'x': 'k'}. However, I should get "11, 20, 30" (or something similar with that data, since csvDict is supposed to automatically use the first line as a header. When I print the file in pdb I get: 'xk,ab,cd\n11,20,30\n31,27,35' etc. How can I properly read the csv file? -
Mapping Django URLs in JQuery append()
I am appending an anchor tag dynamically after an AJAX call completes, but I'm not able to set the href attribute of it as a Django URL. Here's my code: $maincontent.append("<a id='resultslink'>Get results here</a>"); $('#resultslink').attr('href', "{% url 'results' %}"); Django gives the following error - The current path, InitialWebApp/hdfs/{%, didn't match any of these. Apparently, Django thinks {% is the href value. -
How to append table row in django template having for loop?
I have a table whose rows are generated by a for loop in Django template. Sample Table Note that blank fields are table columns to be filled (this table acts as a form). When the user clicks on plus button then there should a new row just below it. and can someone suggest me that, how can I handle these values on view function when user post this form. -
Images in Django
I am looking to display an image from my media folder in Django. I currently have the media root set up, but it keeps searching inside of the stocks folder for the image. How do I get the image in that folder to display settings.py- STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), #'/var/www/static/', ] MEDIAFILES_DIRS = [ os.path.join(BASE_DIR, "media") ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn') MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') search.html (template) - <!doctype html> <html lang="en"> <head> <!--<meta charset="utf-8">--> <title>Stock Information</title> <!-- meta name="description" content="The HTML5 Herald"> <meta name="author" content="SitePoint"> < <link rel="stylesheet" href="css/styles.css?v=1.0"> <[if lt IE 9]> <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script> <![endif]--> </head> <body> <h1> This is the page </h1> <img src = "{{ MEDIA_ROOT }} stocks_graph.png" alt = "Stock Graph"> <!-- script src="js/scripts.js"></script --> </body> </html> Error Message - Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/stocks/stocks_graph.png Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ ^stocks/ ^$ ^media\/(?P<path>.*)$ ^static\/(?P<path>.*)$ The current path, stocks/stocks_graph.png, didn't match any of these. urls.py - from django.conf.urls import include, url from django.contrib import admin from stocks import views from stocks import urls from django.conf import settings from django.conf.urls.static import static from django.views.generic import … -
Django search only working on one url
https://www.youtube.com/watch?v=L1Zpgo-7dhg As you can see with the current setup I have it only allows things to be searched from one url and it will not work on the others. Is there a way to make the search independent of the url and to just insert the query value on the end of a string and then be sent to that page? Or is there a better way of doing it? Views.py class Productlistview(ListView): model=product template="product_list.html" def get_queryset(self ,*args ,**kwargs): qs=super(Productlistview,self).get_queryset(**kwargs) query=self.request.GET.get("q") # print (query) if query: qs =qs.filter(Q(title__icontains=query)|Q(desc__icontains=query) ).order_by("-title") #print (query) return(qs) Search.html <form class="navbar-form navbar-right" method="GET" action=""> <input class="form-control search-field" type="search" name="q" placeholder="Search" value='{{request.GET.q}}'> Urls.py from django.conf.urls import url ,include from django.contrib import admin from .views import (detail_view ,list_view ,detail_slug_view, create_view,update_view,Productlistview , ListView,Productdetailview, productcreateview, productupdateview, Productdownloadview ) from products.forms import ProductModelForm urlpatterns = [ url(r'^$',Productlistview.as_view(),name='list'), url(r'^add/$',productcreateview.as_view(),name='create_'), url(r'^(?P<pk>\d+)/$',Productdetailview.as_view(),name='detail'), url(r'^(?P<slug>[\w-]+)/$',Productdetailview.as_view(),name='detail_slug'), url(r'^(?P<pk>\d+)/edit/$',productupdateview.as_view(),name='update'), url(r'^(?P<slug>[\w-]+)/edit/$',productupdateview.as_view(),name='update_slug'), url(r'^(?P<pk>\d+)/download/$',Productdownloadview.as_view(),name='download'), url(r'^(?P<slug>[\w-]+)/download/$',Productdownloadview.as_view(),name='download_slug'), ] Any help would be appreciated :) -
Error in using VueJS inside PyCharm
I am working on a Python Django project in which in one of the app, I have to do a lot of DOM manipulations. Earlier, I was using jQuery for this purpose but I want to use VueJS because of its virtual DOM. I am using PyCharm Pro. I am not able to use .vue files inside PyCharm. Somehow, I mistakenly set the 'language setting' for .vue file to React RxJS (since Vue also supports RxJS). I then installed Vue plugin for PyCharm and restarted it. Still, I get the same error "Unidentified character <" in the template portion of Vue file. I found that VueJS is now supported with a plugin in PyCharm Pro (https://twitter.com/pycharm/status/848978918120058880). Can someone tell me what I am missing? What changes in the project or PyCharm settings do I need to make? Edit: If someone can, please provide any suggestions/alternative solutions to handle DOM manipulations other than jQuery. -
populate text file to database
I'm trying to read from a text file that contains a bunch of words line by line. I tried to use this question's solution but I couldn't do it. This is how I setup my models.py file: from django.db import models class words(models.Model): wordslist = models.CharField(null='True', max_length=128) I tried to run this code in the python manage.py shell: from app.models import words WORDLIST_FILENAME = "app/words.txt" inFile = open(WORDLIST_FILENAME, 'r') wordlist = [] for line in inFile: wordlist.append(line.strip().lower()) # wordlist: list of strings words.objects.create() This doesn't end up completing and I have to keyboard interrupt. I'm using Django 1.11 -
Django: queryset.count() is significantly slower on chained filters than single filters regardless of returned query size--is there a solution?
I've been struggling with a problem I haven't seen an answer to online. When chaining two filters in Django e.g. masterQuery = bigmodel.relatedmodel_set.all() masterQuery = masterQuery.filter(name__contains="test") masterQuery.count() #returns 100,000 results in < 1 second #test filter--all 100,000+ names have "test x" where x is 0-9 storedCount = masterQuery.filter(name__contains="9").count() #returns ~50,000 results but takes 5-6 seconds Trying a slightly different way: masterQuery = masterQuery.filter(name__contains="9") masterQuery.count() #also returns ~50,000 results in 5-6 seconds performing an & merge seems to ever so slightly improve performance, e.g masterQuery = bigmodel.relatedmodel_set.all() masterQuery = masterQuery.filter(name__contains="test") (masterQuery & masterQuery.filter(name__contains="9")).count() It seems as if count takes a significantly longer time beyond a single filter in a queryset. I assume it may have something to do with mySQL, which apparently doesn't like nested statements--and I assume that two filters are creating a nested query that slows mySQL down, regardless of the SELECT COUNT(*) django uses So my question is: Is there anyway to speed this up? I'm getting ready to do a lot of regular nested querying only using queryset counts (I don't need the actual model values) without database hits to load the models. e.g. I don't need to load 100,000 models from the database, I just need … -
Why does Daphne fail when run through supervisor, but works when run on command line?
I am trying to use supervisor to manage a Daphne server and a few workers for a Django application in AWS. I have been following this tutorial. My supervisord.conf looks like this: ; supervisor config file [unix_http_server] file=/var/run/supervisor.sock ; (the path to the socket file) chmod=0770 ; socket file mode (default 0700) chown=root:supervisor [inet_http_server] port = 9001 username = nte_user # Basic auth username password = generated-passphrase # Basic auth password [supervisord] logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log) pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) childlogdir=/var/log/supervisor ; ('AUTO' child log dir, default $TEMP) ; the below section must remain in the config file for RPC ; (supervisorctl/web interface) to work, additional interfaces may be ; added by defining them in separate rpcinterface: sections [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL for a unix socket ; The [include] section can just contain the "files" setting. This ; setting can list multiple files (separated by whitespace or ; newlines). It can also contain wildcards. The filenames are ; interpreted as relative to this file. Included files *cannot* ; include files themselves. [include] files = /etc/supervisor/conf.d/*.conf My custom config file is located at /etc/supervisor/conf.d/company_name.conf and looks like this (I was trying … -
Deploying project in Docker with Angular 4, Django and postgresql
I am trying to deploy on Heroku my project in Docker with Angular 4 frontend with Django backend and postgresql database. At this moment my files look as shown below. I am note sure if this is done properly? I pushed it using heroku container:push web --app myproject but it doesn't work (Logs). I assume that if I use Docker I don't have to create Procfile etc.? May the error be caused by lack of migration of database? I have no idea that I'm moving into the right direction but I'm trying to migrate my database. Maybe my error is caused by lack of db? When I run heroku run python manage.py migrate, I get: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Logs: 2017-07-07T10:27:30.448951+00:00 heroku[web.1]: State changed from crashed to starting 2017-07-07T10:27:30.436282+00:00 heroku[web.1]: Process exited with status 0 2017-07-07T10:27:50.846928+00:00 heroku[web.1]: Starting process with command `python3` 2017-07-07T10:27:53.350381+00:00 heroku[web.1]: Process exited with status 0 2017-07-07T10:27:53.365013+00:00 heroku[web.1]: State changed from starting to crashed 2017-07-07T10:27:53.876208+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=e1f8edfc-7dc4-4bd3-91be-0a853e948452 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https 2017-07-07T10:28:43.444860+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=361846d1-41cd-403a-989f-4c29a0d1179e fwd="109.173.154.199" dyno= connect= service= … -
Django endpoint to upload image fails when submitted from browser but not postman
I'm building a solution that takes screenshots from a web browser and sends it to a django endpoint. The solution works when I use postman to send the information. However when I use my javascript google chrome extension it fails. the information I send is composed of two fields image(text) and dashboard_type(text), views.py class ScreenShotUpload(APIView): def post(self, request, format=None): dashboard_type = request.data.get("dashboard_type", None) image_str = request.data.get("image", None) if dashboard_type is None or image_str is None: return Response({"Error": "invalid entry"}, status.HTTP_400_BAD_REQUEST) if dashboard_type not in [ScreenShot.SH, ScreenShot.WE, ScreenShot.PA, ScreenShot.PR]: return Response( {"Error": "invalid dashboard_type, must be either PA, PR, SH or WE"}, status.HTTP_400_BAD_REQUEST) ScreenShot.objects.filter(is_latest=True).update(is_latest=False) new_screenshot = ScreenShot(dashboard_type=dashboard_type, is_latest=True) new_screenshot.set_image_path() new_screenshot.save_image_str(image_str) new_screenshot.save() return Response({"status": "200"}, status.HTTP_200_OK) chrome-extension.js var id = 100; chrome.browserAction.onClicked.addListener(function() { chrome.tabs.captureVisibleTab(null, {format: "jpeg", quality: 100}, function(screenshotUrl) { var xhr = new XMLHttpRequest() , formData = new FormData(); formData.append("image", screenshotUrl); formData.append("dashboard_type", "SH"); xhr.open("POST", "http://intranet/api/powerbi/screenshots_upload/"); xhr.send(formData); var viewTabUrl = chrome.extension.getURL('screenshot.html?id=' + id++) var targetId = null; }); }); As I wrote above, when I use postman to send the image as a base64 string that represents an image it works but when I use this script it fails(image corrupted) the size of the image is smaller when I send it with …