Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name '..' from partially initialized module '..' (most likely due to a circular import)
I have an app with a form that has been working fine until now. I'm not sure what I did to cause this error since it's been working fine for months now. I've tried changing the file names, where I import the models, nothing is working I'm attaching relevant parts of my code : This is my models.py class SingleEnd(models.Model): file = models.FileField(upload_to='documents/') email = models.CharField(max_length=100) def __str__(self): return self.email THis is my forms.py from app.models import SingleEnd class SingleEndForm(forms.ModelForm): class Meta: #shows which model to use from models.py model = SingleEnd #fields = 'all' fields = ['file', 'email'] labels = { 'file': 'input your fasta/fastq file (min 3 sequences)', 'email':'input your email to get a notification for your results in a timely manner', } widgets = { 'email':forms.EmailInput(attrs={'class':'form-control'}), 'file':forms.FileInput(attrs={'class':'form-control'}), } This is my views.py #defines a view function def snippet_detail(request): #path to save inputs media_path = "/home/project/media/documents/" #path to save outputs result_path = '/home/project/media/results' max_timeout = 1246060 #dayshoursminssecs #dictionary-like object that uses form data if request.method == 'POST': #use the form to upload form info (post) and files form = SingleEndForm(request.POST, request.FILES) if form.is_valid(): #saves full form form = SingleEndForm(file=request.FILES['file']) form.save() #changes file name if the name is the … -
404 Error message in Django after hitting the submit button
I got a the following error in Django after clicking the submitbutton in the browser: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/send Using the URLconf defined in contactform.urls, Django tried these URL patterns, in this order: admin/ [name='index'] The current path, send, didn’t match any of these. i have two urls in my code. They are: django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), ] and from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), ] How can i solve this? I Hope that you have a solution to this problem. Kind Regards Win -
how to post data of two models in single view.py using serializer? django rest framework
Suppose I've 2 models created namely: booking and passenger. Both have a relationship of Many-to-many. Now, without using a nested serializer, how do I use both models' serializers to post data inside DB? model.py class Passenger(models.Model): name = models.CharField(max_length=100,blank=True, default='') contact_number= models.IntegerField() email = models.EmailField(max_length=254) gender = models.IntegerField(choices=GENDER_CHOICES) age= models.IntegerField() user=models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name class Booking(models.Model): user =models.ForeignKey(User,on_delete=models.CASCADE) flights =models.ForeignKey(Flight,on_delete=models.CASCADE) **passenger =models.ManyToManyField(Passenger)** booking_number= models.IntegerField(default=0, blank= True) booking_time = models.DateTimeField(auto_now=False, auto_now_add=False) no_of_passengers= models.IntegerField(default=0, blank= True) def __str__(self): return self.booking_number and the Corresponding serializer serializer.py class PassengerSerializer(serializers.ModelSerializer): class Meta: model= Passenger fields = '__all__' class BookingSerializers(serializers.ModelSerializer): class Meta: model= Booking fields = '__all__' Now what I've to do is that in views.py I'm creating "class BookingAPIView(APIView):" NOw in this I've to use POST method def post(self, request, format=None): bookserializer = BookingSerializers(data=request.data) passengerserializer = PassengerSerializer(data=request.data) HOW to save data from both serializers in this single POST method? view.py class BookingAPIView(APIView): def get(self, request, format=None): bookings = Booking.objects.all() serializer = BookingSerializer(bookings, many=True) return Response(serializer.data) def post(self, request, format=None): bookserializer = BookingSerializers(data=request.data) passengerserializer = PassengerSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Create and persist service object in root of django app
I've created a basic django app that has a custom library installed (uses Asyncio). I need to instantiate a factory class from the library and then use it to get some service objects back to use in the app. creds = load_creds('./creds.json') async with TestFactory(creds) as factory: tickets = factory.get_ticket() results = await tickets.find_by_number('IN12345678') print (results.ticket_group) I've only been looking at Django for the last few days. So I'm not sure where is best to place this code. I just need it to persist the service objects I'm generating from the factory class and make them accessible to the rest of the app for as long as the app is running i.e. scaffold once, always accessible. From a c# perspective, I could do this during app startup and pass it down via DI. -
Django Ajax success send context in new url
I have a first page with a Launch button, the process is done and them all is redirect to a result page where I can download the different results. Without Ajax and with "regular" Django, the process is working. However, because of other functionalities in the first page, I have to work with Ajax. And if I do not redifined the success part of Ajax, nothing is appenning.. I have a function view for the first page : def launchCtd(request): """ This Function is activate when user click on the launch button of the convertToDose page. It receive the request, create the JSON file and launch the ConvertToDose Analysis. Then it redirect to the Result page """ if request.method == 'POST': #DO stuff context = { 'filename': img_out_path, 'protocol_file': json_pactrlRectth, } #return render(request, 'result.html', context) return JsonResponse(context, safe=False)# I trie to pass the url but it was not a success... else: #Ini Forms context = { #Send Forms } return render(request, 'template.html', context) the template of the first page (only ajax part) $.ajax({ url: "", type: "POST", data: formData, processData: false, contentType: false, beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", $('input[name="csrfmiddlewaretoken"]').val()); }, success: function(data){ //print okay with JSONResponse in view console.log(data.protocol_file) … -
Django REST framework: Serializer to use max_length from model
I have a model class Person(models.Model): name = models.CharField(max_length=254) and related serializer class PersonSerializer(serializers.Serializer): name = serializers.CharField(max_length=254) Is there a way to make CharField automatically detect max_length from the model and use that in validation? Using Person._meta.get_field('name').max_length could be an option but feels a bit cumbersome to be used in every field. Maybe overriding CharField with custom implementation? Or is there other options? -
Django REST view + celery
I would like to create a new GET or POST endpoint (which will be better?) to run specific celery task. In JSON body I will provide a text, and depends of this text the needed task will be launched. If in body I will provide - 'first', then task generate_first_results will be launched. If 'second', then generate_second_results will be launched. If 'third', then generate_third_results will be launched. I have created: urls.py router.register('get_results', views.ResultsViewSet, basename='get_results') views.py class ResultsViewSet(viewsets.ViewSet): def get(self, request): logger.info('Running results') try: # need to make a separation depending of the body generate_first_results.delay() generate_second_results.delay() generate_third_results.delay() return Response(status=status.HTTP_202_ACCEPTED) except Exception as e: logger.debug('Failed', e) return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
How to use __ (double underscore) in SQLAlchemy query like django ORM
I have 3 models @dataclass class Plans(db.Model): id = db. Column(db.Integer, primary_key=True, autoincrement=False) name = db.Column(db.String(100), nullable=True,) feature = db.relationship('PlanFeatures', backref = 'planfeatures') def __str__(self): return str(self.name) @dataclass class PlanFeatures(db.Model): id = db. Column(db.Integer, primary_key=True, autoincrement=False) plan_id = db.Column(db.Integer, db.ForeignKey('plans.id')) feature = db.Column(db.String(100), nullable=True,) plan = db.relationship('Plans', backref ='planfeatures') def __str__(self): return str(self.feature) @dataclass class UserPlans(db.Model): id = db. Column(db.Integer, primary_key=True, autoincrement=False) plan_id = db.Column(db.Integer, db.ForeignKey('plans.id')) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True,) def __str__(self): return str(self.plan_id) In Django For example plan_of_user=UserPlans.objects.get(,plan__plan_features__feature=feature_choice) where feature_choice is my value. How to write a query filter equivalent to this in flask SQLAlchemy? Thanks in advance -
django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found
Tried all the possible suggested ways available on the internet based on my research but still got the same error. Error : django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') Kindly refer to the codes below. views.py def home(request): if request.method=="POST": con=pyodbc.connect( r'Driver={ODBC Driver 17 for SQL Server};' r'Server=srver;' r'Database=data;' r'USER=admin;' r'PASSWORD=1234;' ) cursor=con.cursor() cursor.execute("select Email, EmployeeID from [data].[dbo].[profiles] where EmployeeID='45678'") result=cursor.fetchall() cursor.close() return render(request, 'index.html',{'databasecon':result}) models.py from django.db import models # Create your models here. class databasecon(models.Model): empid=models.CharField(max_length=8) email=models.CharField(max_length=50) settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'data', 'USER':'admin', 'PASSWORD':'1234', 'HOST':'PROD123', 'PORT':'8000', 'OPTIONS':{ 'driver':'ODBC Driver 17 for SQL Server', 'isolation_level':'READ UNCOMITTED' #to prevent deadlocks } } } -
dj-rest-auth token not deleted in backend after logout
I started using the django dj-rest-auth package with react and i ran across the following issue: When i logout it will clear the key inside the local storage but not inside the Django backend. When i go to the API endpoint page and click the "send post request" button it will do it, but it won't do it when i use my frontend to logout. This is the code i'm using to accomplish this: navbar.js import { useContext } from "react"; import { Link, useNavigate } from "react-router-dom"; import axios from "axios" import { AuthContext } from "../contexts/AuthContext"; import { API } from "../api" export function Navbar() { const { user, logout } = useContext(AuthContext) const navigate = useNavigate() function handleSubmit() { axios.post(API.auth.logout) .then(res => { logout() navigate('/login') }) } api.js const baseURL = "http://127.0.0.1:8000" const apiURL = `${baseURL}/api` export const API = { auth: { login: `${baseURL}/dj-rest-auth/login/`, logout: `${baseURL}/dj-rest-auth/logout/`, passwordReset: `${baseURL}/dj-rest-auth/password/reset/`, passwordResetConfirm: `${baseURL}/dj-rest-auth/password/reset/confirm/`, signup: `${baseURL}/dj-rest-auth/registration/`, verifyEmail: `${baseURL}/dj-rest-auth/registration/verify-email/` } } app.js import React, { useContext } from "react"; import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom"; import { AuthContext, AuthContextProvider } from './contexts/AuthContext' import { Login } from './components/Login' import { Reset } from './components/Reset' import { … -
Combining custom django crispy forms' FormHelper and HttpResponse with context
I am working on a django project with an app which has lots of related fields like ForeignKey and ManyToManyField. There is a Model that I can call it "OriginModel" for I can access all other models through it. I've tried to render this model with a template and form using context but it seems like not manageable or hard to manage further changes and additions. Because I was hardcoding one OriginModel's all relations in a template. I've changed my method by using inclusive tags for repeating relations but I think it's a bad practice for manageability reason once again for my case. So I've changed my method again. I've tried crispy forms' FormHelper and Layout classes to create OriginModel's form. But I've faced a problem: I couldn't populate related fields with this method. Only OriginModel's direct fields (like "initials" in the code below) could be rendered. And after this failure I coded classes like FormHelper and Layout but my classes have functions to return html string just like my template file, so those are like HTML generators with extra steps I think. Because these classes have been built to return html ultimately, I used HttpResponse in the view of … -
How to color in region based on postal code using Leaflet?
I'm trying to color in an entire region on my map based on a Postal Code. So I want the entire postal code region to be colored in basically. I am using the plugin Leaflet for this. Right now I display circles on the map (Click the link to see): Current Map This is the JS code I am using to display it: $(document).ready(function(){ /* Initialising the map */ var map = L.map('map').setView([50.84673, 4.35247], 9); L.tileLayer('https://tile.openstreetmap.be/osmbe/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors' + ', Tiles courtesy of <a href="https://geo6.be/">GEO-6</a>', maxZoom: 18 }).addTo(map); var popup = L.popup(); function onMapClick(e) { popup .setLatLng(e.latlng) .setContent("You clicked the map at " + e.latlng.toString()) .openOn(map); } map.on('click', onMapClick); // Fetching the postal codes for each representative $.ajax({ url: dynamicmapurl, method: "GET", dataType: 'json', beforeSend: function(xhr, settings) { if(!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, success:function(data) { data = data.reverse(); for(var i = 0; i < data.length; i++){ //Drawing a circle on the map based on the //Postal code dictionary array I'm receiving from the backend L.circle([data[i].lat, data[i].lon], 500, { color: data[i].fillColor, fillColor: data[i].fillColor, fillOpacity: 0.8 }).addTo(map).bindPopup("Vertegenwoordiger: " + data[i].vertegenwoordiger + " <br> " + " Postcode: " + data[i].postcode) } }, error: function(data){ console.log(data); … -
why django tearDown does not delete the test data after exception in tests?
I created an exception in the test function but after this exception, tearDown did not delete data from the database. def test_duty_sync_data_daily(self): duties, device_id = factory_boy_create_fake_data() url_duty = reverse('habit:duty-sync-data') response_duty = self.user.post( url_duty, data=duties, HTTP_USER_AGENT='Mozilla/5.0' ) self.assertEqual(response_duty.status_code, status.HTTP_200_OK) raise Exception -
Elastic Beans + Django. Switch HTTP to HTTPS using Load Balancer
Dear Stackoverflow community. This question has been asked before, but my question is little bit different. So I am using Elasticbeanstalk to deploy my Django Backend and RDS for database (PostgreSQL). EB generated a link for my backend --> http://XXXXX.region.elasticbeans.com. The issue is that when I send a request from the frontend side (HTTPS), it gives a "Blocked loading mixed active content" error, which comes from HTTPS to HTTP request. As far as I am concerned I have to change configuration of the Load Balancer of my EC2 instance and add redirection. In order to successfully do that I am required to have a SSL certificate. However, when I use ACM (Certificate Manager) in order to generate one using the exact same link for the backend, it automatically rejects my request. So my question is that what is the exact process of obtaining the SSL cert. for the default EB link, or maybe there are easier ways to redirect HTTP to HTTPS from the AWS console? Regards. -
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` DRF
I am receiving the error Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> In Django DRF, in my query i am trying to get the count of all related items to one specific item the views.py @api_view(['GET']) def getVesselInfo(request): vessels = (Vessel.objects.annotate( Count('vessel_components', distinct=True))) vSerializer = VesselSerializer(vessels, many=True) return Response(vSerializer.data,) models.py: class Vessel(models.Model): name = models.CharField(max_length=255) imo = models.CharField(max_length=255) def __str__(self): return self.name class Component(MP_Node): name = models.CharField(max_length=255, blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) type = models.CharField(max_length=200, blank=True, null=True) remarks = models.TextField(blank=True, null=True) vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components') def __str__(self): return self.name -
How to extract desired value from queryset value of dict type using annotate d in Django
[views.py] from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') histories = History.objects.filter(summary__icontains='teacher', date__gte=from_date, date__lte=to_date).order_by('date').annotate(teacher=F('summary')).values('study_name', 'teacher', 'date') return render(request, 'charts.html', { 'histories': histories, 'from_date': from_date, 'to_date': to_date }) The History model has summary and create_date fields. To check the type of the field value in the template, make and check get_type template tag and the summary field was a dict type. I don't need the entire summary field value, I just want to extract the teacher value and store it in a temporary field called 'teacher' using annotate. entire summary field value is: {'field_summary': {'recruiting': 'None -> Yes', 'teacher': 'None -> Halen', 'subject': None -> 'science'}, 'file_summary': {}} So the result I want is: [charts.html] {{ histories }} [display] <QuerySet [{'study_name': 'math', 'create_date': datetime.datetime(2022, 1, 4, 0, 24, 33, 357339, tzinfo=<UTC>), 'teacher': 'None -> Halen'}, {'study_name': 'science', 'create_date': datetime.datetime(2022, 3, 2, 10, 10, 33, 733339, tzinfo=<UTC>), 'teacher': 'None -> Kevin'}, {'study_name': 'music', 'create_date': datetime.datetime(2022, 2, 10, 3, 11, 33, 738452, tzinfo=<UTC>), 'teacher': 'Mark'}]> I want to get the queryset value in dict format by utilizing annotate in django's views.py. -
Custom permissions in django isn't working
I want to add custom permissions: Only admin and owner of the object can modify the object All registered users can view the objects My solution: SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') class IsApplicationAdmin(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: if request.user.is_superuser or request.user.user_type == "Admin": return True if request.method in SAFE_METHODS: return True def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.user_name == request.user # owner can modify the object PROBLEM -- for PATCH request (partial update) http://127.0.0.1:8000/api/admin_panel/users/2/ I have this error { "detail": "You do not have permission to perform this action." } I was debugging the code and see debugging log only in has_permission (no logs in has_object_permission) What should I fix? I was reading https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions and the table said that PATH request relates to object permissions -
How do I test for str equality using factory_boy faker method?
I have two factory classes, the other is linked to the one through foreign key relationships, and was kinda hoping to achieve some similarities with the attributes. To start with, the model looks something like this: class Track(models.Model): response = models.ForeignKey('Response') def __str__(self): return str(self.response) class Response(models.Model): title = models.CharField(max_length=640) def __str__(self): return self.title I should be able to access these classes as I have done below r = Response(title='foo') r.save() t = Track(response=r) t.save() # with this I wanted to test that str(t) == t.response The factory classes look like this: class ResponseFactory(factory.django.DjangoModelFactory): class Meta: model = Response title = factory.Faker('text') class TrackFactory(factory.django.DjangoModelFactory): class Meta: model = Track response = factory.SubFactory(ResponseFactory) Below is how I have accessed these factory classes to test for str equality track = TrackFactory() # generates random string e.g `foo` a = str(track) # == foo b = track.response # == foo # however I get an assertion error with the statement below assert a == b Could you point out where I've gone wrong, thank you. -
Django Password reset view with reactjs
I am a total Django-React fresher. I want to use Django's PasswordResetView Functionality in my Django API with Reactjs as frontend. The Existing functionality is implemented in auth_view which is using templates. Can anybody guide me on how to use it with my custom API? -
I am getting an error message that password does not match in django forms
I am creating a "UsercreationForm" in django. When I saved the form, it didn't create any entry in database then I debug it and found an error message that Password fields does not match I don't know what I did wrong. Please help me figure it out. Here is my forms.py from django import forms from accounts.models import Customer, User from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError from datetime import datetime class UserSignup(UserCreationForm): class Meta: model = User fields = ("username","first_name", "last_name", "email") username = forms.CharField(label="Username", required=True) first_name= forms.CharField(label="First Name", required=True) last_name=forms.CharField(label="Last Name", required=False) email =forms.EmailField(label="Email", required=False) password1 = forms.CharField(label="Password", required=True) password2 = forms.CharField(label="Confirm Password", required=True) def username_clean(self): username = self.cleaned_data['username'].lower() new = User.objects.filter(username = username) if new.count(): raise ValidationError("User Already Exist") return username def email_clean(self): email = self.cleaned_data['email'].lower() new = User.objects.filter(email=email) if new.count(): raise ValidationError(" Email Already Exist") return email def clean_password2(self): password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 != password2: raise ValidationError("Password don't match") return password2 def save(self, commit = True): user = User.objects.create_user( self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1'], last_login= datetime.now() ) return user class AddDetails(forms.ModelForm): class Meta: model = Customer fields = ("age", "phone") age = forms.IntegerField(label="Age", required=True) phone = forms.CharField(label="Mobile Number", required=True) Here is my views.py … -
How to post using reverse in test Django
I have a test, where I try to update my post. In detailview I use pk for each posts. How to send correctly pk in test? I try this but get an error. test: def test_if_user_can_update_news(self): self.client.login(username='test1', password='test1') news = News.objects.get(title='Test news') self.client.post(reverse('update_news', kwargs={ 'pk': news.pk, 'title': 'Updated news'})) self.assertTrue(News.objects.filter(title='Updated news').exists()) error: django.urls.exceptions.NoReverseMatch: Reverse for 'update_news' with keyword arguments '{'pk': 1, 'title': 'Updated news'}' not found. 1 pattern(s) tried: ['news/update_news/(?P<pk>[0-9]+)/\\Z'] -
How to get a download option of dynamic table in Django Database ( each time we will have different tables in Database)
I have tables in Django Data Base with name TBL_Result_1_1, TBL_Result_1_2 etc. Image of All tables in Django Backend I want to provide a download option in agnular frontend to download all TBL_Result.. tables provided these tables name are not permanent, more tables will add with name TBL_Result.. in django database. I have used models.py for static tables in django, but these tabbles are dynamic. Will not able to add models.py each time for each table. -
Month on month values in django query
I have an annotation like this: which displays the month wise count of a field bar = Foo.objects.annotate( item_count=Count('item') ).order_by('-item_month', '-item_year') and this produces output like this: html render I would like to show the change in item_count when compared with the previous month item_count for each month (except the first month). How could I achieve this using annotations or do I need to use pandas? Thanks -
How to perform n time or query using ORM?
I have an array of values values['value1','value2'....n] I want to perform the following query res = TheModel.objects.filter(key=values[0] or key = values[1] or key = values[2]...n) Here the problem is array size may be different every time. How can I achieve this? -
403 forbidden for presigned_url upload
I have 403 error when uploading presigned url At first, I exec s3.generate_presigned_post in local temp = s3.generate_presigned_post( "my-resource-bucket-v","test" ) and get the url and fields {'url': 'https://my-resource-bucket-v.s3.amazonaws.com/', 'fields': {'key': 'test', 'AWSAccessKeyId': 'AKIAZ3YPMLASV6736UA4', 'policy': 'eyJleHBpcmF0aW9uIjogIjIwMjItMDUtMDlUMDY6MDU6MTNaIiwgImNvbmRpdGlvbnMiOiBbeyJidWNrZXQiOiAic2kyLXMzLXNidS1qb2ItaHVudGluZy1keC10b2t5by1qeGMtc3RhdGljLXJlc291cmNlLXYifSwgeyJrZXkiOiAidGVzdCJ9XX0=', 'signature': 'F7E074YWIVwy4ZL2zXSv8YVTbyE='}}" then I try this to upload curl -v -X POST \ -F key="{'key': 'test', 'AWSAccessKeyId': 'AKIAZ3YPMLASV6736UA4', 'policy': 'eyJleHBpcmF0aW9uIjogIjIwMjItMDUtMDlUMDY6MTE6MjhaIiwgImNvbmRpdGlvbnMiOiBbeyJidWNrZXQiOiAic2kyLXMzLXNidS1qb2ItaHVudGluZy1keC10b2t5by1qeGMtc3RhdGljLXJlc291cmNlLXYifSwgeyJrZXkiOiAidGVzdCJ9XX0=', 'signature': 'GNUthYj0cec9uIQjeJsuap7OTfk='}" \ -F policy="{'key': 'test', 'AWSAccessKeyId': 'AKIAZ3YPMLASV6736UA4', 'policy': 'eyJleHBpcmF0aW9uIjogIjIwMjItMDUtMDlUMDY6MTE6MjhaIiwgImNvbmRpdGlvbnMiOiBbeyJidWNrZXQiOiAic2kyLXMzLXNidS1qb2ItaHVudGluZy1keC10b2t5by1qeGMtc3RhdGljLXJlc291cmNlLXYifSwgeyJrZXkiOiAidGVzdCJ9XX0=', 'signature': 'GNUthYj0cec9uIQjeJsuap7OTfk='}" \ -F file=myimage.png https://my-resource-bucket-v/ It returns like this. I think bucket policy of S3 is not relevant with presigned_url, So,, where the permission error occurs?? Note: Unnecessary use of -X or --request, POST is already inferred. * Trying 52.219.196.109:443... * Connected to my-resource-bucket-v.s3.amazonaws.com (52.219.196.109) port 443 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: /etc/ssl/cert.pem * CApath: none * TLSv1.2 (OUT), TLS handshake, Client hello (1): * TLSv1.2 (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (IN), TLS handshake, Server key exchange (12): * TLSv1.2 (IN), TLS handshake, Server finished (14): * TLSv1.2 (OUT), TLS handshake, Client key exchange (16): * TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1): * TLSv1.2 (OUT), TLS handshake, Finished (20): …