Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Virtual Trading Platform with Django Rest Framework (Good Idea)?
Trading application relies on many requests is it advisable to build the API backend with Django rest framework with scalability in mind? Any suggestions would be great. -
ListView with an extra argument
I want to add a parameter somevar to my listview: {% url 'products' somevar %}?" in the urls: path("products/<int:somevar>", ProductListView.as_view(), name = 'products'), in the views: class ProductListView(ListView): def get_template_names(self): print(self.kwargs) # {"somevar": xxxxx} return f"{TEMPLATE_ROOT}/products.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.get_products().order_by("number") print(kwargs) # kwargs is {} here return context def get_queryset(self): return super().get_queryset().order_by("number") How can I pass the variable to the get_context_data method? I tried defining a get method and call self.get_context_data(**kwargs) within, but this leads to an object has no attribute 'object_list' error. -
Ajax not getting data from Django view
I have a page that the user is supposed to type in the URL to a YouTube video. That URL is sent with Ajax to a Django view that checks the URL to see if its valid or not. Then it alerts with either an error message is if its not valid, or alerts with the video title if it valid. The alerts are done with the standard javascript alerts. This is just a test version of the page. I plan to display the info gathered from video on the page itself. This is the template for the page. <body> <form method="post"> {% csrf_token %} <input type="text" name="url" id="url"> <label for="url">Please Enter Video URL Below</label> <button id='button'></button> <p id = 'test'></p> </form> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> <script> document.getElementById('button').addEventListener('click', find_video, false) function find_video(){ var url = document.getElementById('url').value; $.ajax({ url: "ajax/find_video/", type: "POST", data: { csrfmiddlewaretoken: window.CSRF_TOKEN, url : url}, dataType: 'json', complete: function(data){ if (data.error_message){ alert('Please enter valid url') } else { alert(data.video_title) } }, }); } </script> </body> </html> This is the Django view def find_video(request): url = request.POST.get('url') #unquotes url formating so youtube_dl can use it. urllib.parse.unquote(url) if is_valid(url): error_message = False else: … -
Django Save User Responses for Next Visit - Caching or Sessions?
I have a user review system where managers can review their employees access to specific systems. The table they are presented with looks something like this <table class="employeeTable" id="employeeTable"> <thead> <tr> <th>Status</th> <th>Employee Name</th> <th>PID</th> <th>Title</th> <th>Email</th> <th>Enabled in System</th> <th>System Permission Group</th> <th>System Name</th> <th>Approve</th> <th>Deny</th> <th>Reasoning</th> </tr> </thead> <tbody> <tr> <td class="statusCircle" accessCorrect="False"><svg class="statusCircle" style="margin-left:5px;" xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="grey" stroke="#be9b9b" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle></svg></td> <td>Last, First</td> <td>Emp ID</td> <td>Emp title</td> <td>first.last@email.com</td> <td>true</td> <td>Permissions</td> <td>System Emp ID</td> <td class="approvePerm"><svg class="approvePerm" style="float:right;" class="tableButtons" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#43a600" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg></td> <td class="denyPerm"><svg class="denyPerm" style="float:right;" class="tableButtons" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#d90e0e" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></td> <td><select class="reason" style="display: none;"> <option>No longer employed with Company</option> <option>Job role no longer requires this access</option> <option>Employee has transferred</option> </select></td> </tr> <tr> <td class="statusCircle" accessCorrect="False"><svg class="statusCircle" style="margin-left:5px;" xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="grey" stroke="#be9b9b" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle></svg></td> <td>Last, First</td> <td>Emp ID</td> <td>Emp title</td> <td>first.last@email.com</td> <td>true</td> <td>Permissions</td> <td>System Emp ID</td> <td class="approvePerm"><svg class="approvePerm" style="float:right;" class="tableButtons" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#43a600" … -
First time deploying a django app on Heroku and I'm facing 2 issues, solution?
I've worked on my social app and been able to deploy it and I'm having 2 problems: Link: https://network50web.herokuapp.com/ 1/It directs me autmatically to https://network50web.herokuapp.com/accounts/login/?next=/ and I'm only able to see the site if I write the routes manually in the address bar like(login, register) 2/When I try to login it with my existent username it throws error "Programming Error at /login relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user..." and it highlights this line " user = User.objects.create_user(username, email, password)" even when I try to register a new account I used SQL for the database Views: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect, request from django.http.response import JsonResponse from django.shortcuts import render, redirect, resolve_url, get_object_or_404 from django.urls import reverse, reverse_lazy from django.core import serializers from django.core.paginator import Paginator from django.contrib import messages from django.contrib.auth.models import User from django.db.models import Q from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from itertools import chain from .models import Relationship, Post, Profile, Like from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView from .forms import ProfileModelForm, PostModelForm, CommentModelForm def search_view(request): if request.method == "POST": searched = request.POST['searched'] profiles = Profile.objects.filter(slug__contains=searched) return render(request, … -
Django displaying uploaded images
I am working on an application that allows users to upload PDFs. I want to display the PDFs in various templates. I am using multi-tenant so that may be an issue. So far, I haven't been able to get the PDFs to display. In the place of the image I see: Page not found (404) Request Method: GET Request URL: http://co1.localhost:8000/projects/project/1/document/2/projects/documents/012022/Joint1021S.pdf The view: class ProjectDocumentsDetailView(DetailView): model = ProjectDocuments id = ProjectDocuments.objects.only('id') template_name = 'company_accounts/project_document_detail.html' The template: {% extends 'base.html' %} {% block content %} <div class="section-container container"> <div class="project-entry"> <h2>{{ projectdocuments.title }}</h2> <p>{{ projectdocuments.description | safe }}</p> <embed src="{{ projectdocuments.file }}" <img src="{{ projectdocuments.file }}"> <p>{{ projectdocuments.file }}</p> </div> <div> </div> {% endblock content %} In the main site config/urls I have the line: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The files (in this specific instance) are stored in a file in media>company1>documents>012022>file.pdf From the error, at least one issue appears to be the way the path to the pdf is being constructed. Any ideas about how to fix this? -
Show request duration in drf-spectacular (Swagger)
I have a Django/DRF project with drf-spectacular (Swagger) integration and wondering how can I add a request duration as shown on the image below. Is there any way to achive elapsed time section? Thanks in advance. -
Django Rest Framework: how to route a uuid to an associated object?
I am building a simple photos-albums app with Django Rest Framework (DRF). Each album has a UUID field in its model. I want to create 'share links' so that someone with a link of the form /albums/[uuid] will be able to access that album. I am using ModelViewSet for my views, so I assume that the most succinct way to achieve this desired routing is via the action decorator, with urls like /albums/shared/[uuid], but it's not clear to me how to obtain the uuid in the action-decorated shared method. I can't even parse the URL because DRF will 404 before firing this shared method: ### views/album.py class AlbumViewSet(viewsets.ModelViewSet): queryset = Album.objects.all() serializer_class = AlbumSerializer @action(detail=False, methods=['get']) def shared(self, request): # How do you get the uuid from the supplied URL? uuid = ??? obj = self.get_queryset().objects.get(uuid=uuid) return Response([obj]) Hopefully I won't have to add any fancy patterns to urls.py, but if I do then here is what I have so far: ### myapp/urls.py router = routers.DefaultRouter() router.register(r'albums', AlbumViewSet) ... urlpatterns = [ # ... path('', include(router.urls)), ] format_suffix_patterns(urlpatterns) Thanks! -
How to add data to a ManyToMany field model?
I have model Department: class Department(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) subsidiary = models.ManyToManyField('self',null=True,blank=True, symmetrical=False, related_name='subsidiary_name') superior = models.ForeignKey('self',null=True,blank=True, related_name='superior_name', on_delete = models.DO_NOTHING) manager = models.ForeignKey(Manager, on_delete = models.DO_NOTHING) history = HistoricalRecords() def get_subsidiary(self): return "\n".join([p.title for p in self.subsidiary.all()]) def __str__(self): return self.title In Department model I have 2 instance of the same model: subsidiary and superior departments. The rules are simple: one department can have only one superior department, and many subsidiary. I want to implement next logic: I am creating new department SLF, and f.e. I choose SID department as superior department for SLF. Finally, when I save SLF object I want to add this department as subsidiary for SID automatically. I am trying to override save method like: def save(self, *args, **kwargs): print('Department.objects.filter(title=self.superior): ', Department.objects.filter(title=self.superior)) if self.superior__in == Department.objects.filter(title=self.superior.title): tmp = Department.objects.filter(title=self.superior.title) tmp.create(subsidiary = self.superior) tmp.save() super(Department, self).save(*args, **kwargs) But it doesn't work. How can implement something like this? -
Python Django DLL load failed: %1 is not a valid Win32 application
I have a 64 bit architecture system. I installed Python 3.6.0. Project was building and model was compile successfully, but when I install VS Code and install some extensions. My Django Bankend is not working and shown an error:"DLL load failed: %1 is not a valid Win32 application." Any suggestions? -
trying to create a row on a table after making a POST -django
How can I create a new row in table notificacao everytime i make this post? (save is not working i get 'QuerySet' object has no attribute 'save') def post(self, request): cliente1 = Cliente.objects.get(cpf=request.data['cliente1_cpf_transf']) cliente2 = Cliente.objects.get(cpf=request.data['cliente2_cpf_transf']) notificacao1 = Notificacao.objects.all() if cliente1.saldo >= request.data['quantia']: cliente1.saldo -= request.data['quantia'] cliente1.save() cliente2.saldo += request.data['quantia'] cliente2.save() notificacao1.cpf_remetente = request.data['cliente1_cpf_transf'] notificacao1.cpf_destinatario = request.data['cliente2_cpf_transf'] notificacao1.valor = request.data['quantia'] notificacao1.save() -
How to stop SQL injection in Django column of a model
So I know that Django naturally handles sql injections for columns in tables but my team want to do more. We have a help_message table in Django and there is a column in that table called Message which is a string. We do not want to save that message directly as a string in that column because of possible sql injection and malicious use. What can we do to stop sql injection and save that message in the table in Django? -
How exactly does a generic view like DeleteView make your app more scaleable in Django?
My app is currently built exclusively on function-based views, and I'm looking into class based views and especially the generic ones to make it more scaleable - as this is recommended many places. For the class based views in general, I can see the utility as opposed to hundreds of function based views. However - I'm having trouble seeing how the generic ones do anything to save time. I'm trying to figure out the DeleteView now, and it seems to be actually adding more complexity to my code. Currently, a deletion view for me looks like this: views.py def fruit_delete(request, num): fruit = fruits.objects.filter(pk=num) fruit.delete() return redirect(fruits) And all I need to add is a path: urls.py path('fruit_delete/<int:num>', views.fruit_delete, name='fruit_delete'), And a easily replicated button in my templates: <a class="btn btn-danger" href = "{% url 'fruit_delete' fruit.pk %}" onclick="return confirm('Are you sure you want to delete this fruit?')">Delete</a> And this does the job. If I was to need a hundred or so of those views however, it would be beneficial to be able to use the model in question, or other parameters, as arguments in the template itself instead of having to create a separate view + path for every … -
Making a change/Replace the text in a file at specific places in python
I need your help. Currently, I'm developing a Django automation script that will be useful in the future. However, I am unable to replace a specific code snippet with my updated code snippet. Updated code snippets are written at the end of the file, doubling the code snippet in the same file. You can see the code that we (me and Github Copilot) wrote together import os project_name = str(input("Whats your project name : ")).capitalize() apps_name = str(input("What your apps name : ")).split(",") # check if the project name is in the current directory if os.path.isdir(project_name): print("Project name is already in the current directory") exit() else: os.system('cmd /c "django-admin startproject ' + project_name) # change the directory to the project name os.chdir(project_name) # print the current directory print(os.getcwd()) # check if the apps name is in the project directory if os.path.isdir(apps_name[0].capitalize()): print("Apps name is already in the project directory") exit() else: # check if apps_name has more than one app if len(apps_name) > 1: for app in apps_name: os.system('cmd /c "django-admin startapp ' + app.capitalize()) else: os.system('cmd /c "django-admin startapp ' + apps_name[0].capitalize()) # change the directory to the project name os.chdir('../'+project_name) # print the current directory print(os.getcwd()) search_text = … -
How to access the values in nested dictionary sent to django template
I'm sending a nested custom dictionary through my views, that nested dictionary is 'history' def update_participation(request,user_id,event_id): ev=Event.objects.get(id=event_id) data=Participated(user=user_id,event=event_id) data.save() participated=Participated.objects.filter(user=user_id) i=0 #Declared the dictionary history history={} #Adding values to dictionary for partcipate in participated: name=Event.objects.get(id=partcipate.event) name1=name.name fest=Fest.objects.get(id=name.fest_id.id) fest1=fest.name clg=College.objects.get(id=fest.clg_id.id).name history[i]={'event':name1,'fest':fest1,'college':clg} i+=1 messages.success(request,f'You have registered for {ev.name}') #sending the dictionary to template return render(request,'webpage/my_events.html',history) Example of dictionary will look history={0={'event':'css battle','fest':'verve','college':'jss'},1={'event':'code wars','fest':'verve','college':'jss'},2={'event':'hangman','fest':'phase shift','college':'bms'}} I'm trying to access the values css battle,verve,jss like {%extends 'webpage/base.html'%} {%block content%} <h2 style="margin:5px 30px;"><u>My Event History</u></h2> <div style="margin:50px 0px 0px 270px" class='table'> <table border='5'> <tr> <th>Event</th> <th>Fest</th> <th>College</th> </tr> {%for key,value in history.items%} <tr> <td>{{value.event}}</td> <td>{{value.fest}}</td> <td>{{value.college}}</td> </tr> {%endfor%} </table> </div> {%endblock content%} How am I supposed to iterate through the dictionary? -
Django: email sender is the same as the recipient sender , How i can resolve that
I have developed a form contact where the user can contact us he will type his email, the subject and the message, But am stuck on after some tries I didn't succeed to reach my goal , everything is good the email is send to the email recipient that i have mentioned in settings.py EMAIL_HOST_USER But the email sender is registered as the email recipient i do no why ,Here is the code: def contact_view(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, [settings.EMAIL_HOST_USER]) except BadHeaderError: return HttpResponse('Invalid header found.') return render(request, 'pages/success.html') return render(request, 'pages/contact.html', {'form': form}) How i can resolve that i don't want the sender email be the recipient email , i want it to be the email that user will entered during fill out the form. -
Resolve dependency conflict with dash-bootstrap-components, dash, and django-plotly-dash 1.6.6
I am trying to build a docker image for a django web app that has dash and plotly components. However, my build fails with the following error The conflict is caused by: #11 39.72 dash-bootstrap-components 1.0.2 depends on dash>=2.0.0 #11 39.72 django-plotly-dash 1.6.6 depends on dash<1.21.0 and >=1.11 #11 39.72 #11 39.72 To fix this you could try to: #11 39.72 1. loosen the range of package versions you've specified #11 39.72 2. remove package versions to allow pip attempt to solve the dependency conflict I've tried loosening the ranges and removing package versions but am still getting the same error. After some research it appears django-plotly-dash is not updated for dash>2.0 Is there a work around? My webpage works fine locally so I'm not sure why building it is now having the issue. -
How to apply rich text features to the parent element in Wagtail DraftJS?
I am extending Wagtail's DraftJS editor: @hooks.register('register_rich_text_features') def register_uppercase_feature(features): feature_name = 'text-uppercase' type_ = 'UPPERCASE' tag = 'span' control = { 'type': type_, 'label': 'UP', 'description': 'Uppercase', 'style': {'text-transform': 'uppercase'}, } features.register_editor_plugin( 'draftail', feature_name, draftail_features.InlineStyleFeature(control) ) db_conversion = { 'from_database_format': {tag: InlineStyleElementHandler(type_)}, 'to_database_format': {'style_map': {type_: 'span ' 'class="text-uppercase"'}}, } features.register_converter_rule('contentstate', feature_name, db_conversion) features.default_features.append('text-uppercase') The above code works well and applies a element around selected text: <h1><span class="text-uppercase">example text</span></h1> However, how I want to apply my feature to the parent element, h1, not add a span element: example text How can I inherit the parent element? -
I want to query 3 Random Products from the Database everytime only 3
y = (Product.objects.all()).count() x = random.randint(3,y) prouct1 = Product.objects.get(id = x+1) prouct2 = Product.objects.get(id = x-1) prouct3 = Product.objects.get(id = x-2) I want to obtain 3 random products everytime i run a function initially i use the above method But the problem with this is If i delete a object Then i get the error i dont want that thing to happen obviously i can run more checks but i feel there is some simple way to do that The objective is to Get the random object from the database every time the page is renderd -
Conditionally highlight cells in a html table based on the cells' value
The data of my html table is from this list: mylist= [{'StartDate': '2021-10-02', 'ID': 11773, 'Name': Mike, 'Days':66 }, {'StartDate': '2021-10-03', 'ID': 15673, 'Name': Jane, 'Days':65}, {'StartDate': '2021-10-03', 'ID': 95453, 'Name': Jane, 'Days':65}, {'StartDate': '2021-10-03', 'ID': 15673, 'Name': Mike, 'Days':65}, ... {'StartDate': '2021-10-5', 'ID': 34653, 'Name': Jack, 'Days':63}] My HTML table in my HTML file is: <table class="table table-striped" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>StartDate</th> <th>ID</th> <th>Name</th> <th>Days</th> </thead> <body> {% for element in mylist %} <tr> <td>{{ element.StartDate}}</td> <td>{{ element.ID }}</td> <td>{{ element.Receiver }}</td> <td>{{ element.Days }}</td> </tr> {% endfor %} </tbody> </table> I want to set the color of days that are larger than 14 into Red color. And I want to set the cells that contain "Mike" in Red and "Jane" in Blue. Please advise what I should do -
Strange TyperError put() missing 1 required positional argument: 'path'
I've been trying to test my PUT method in the following APITestcase: def test_story_delete(self): c = APIRequestFactory user = User.objects.get(username='test1') payload = {'storyName': 'changetest'} request = c.put(reverse('storyFunctions',args=[self.room.pk,self.story.pk]), format='json') force_authenticate(request,user=user) My URL: path('room/<int:pk>/story/<int:idStory>/adm', APIHstory.as_view(),name='storyFunctions'), And I'm keep receiving this error: TypeError: put() missing 1 required positional argument: 'path' I don't understand what is going on because i declared the path inside request. Can someone help me? -
How Do I Render Form Attributes Manually in Django?
I am trying to render the name attribute manually. {% for language in form.languages %} <div class="form-check"> <input class="form-check-input" id="{{ language.id_for_label }}" name="{{ language.field.name }}" type="checkbox"> <label class="form-check-label" for="{{ language.id_for_label }}">{{ language.choice_label }}</label> </div> {% endfor %} Everything gets rendered nicely except the name attribute of the input tag. form.languages is a ManyToManyField shown on my form as a ModelMultipleChoiceField using the following code in my forms.py. languages = forms.ModelMultipleChoiceField( queryset=Language.objects.all(), widget=forms.CheckboxSelectMultiple ) -
Creating an image field in Django Python, 2022
I'm learning programming (beginner level), and am currently working on a web app project in Python/Django. I would like to add an image field to my models, but the tutorials I find don't seem to work. Does anyone have simple, comprehensive steps to do it? I have run into the following problems: Conflicting PIL vs Pillow imports (I have deleted the PIL imports for now; I have Pillow installed, but not sure if I need to do anything else with it?) When I try to make a migration I get: 'NameError: name 'os' is not defined', which relates to my settings.py file, and which I'm not sure how to resolve. Thank you! -
How to add result from one query into another in Django
I am working on a page that passes trough some parameters. I hava a Projekt modell and a Projekt_szd_by_date model joined in a query. I like to do that to get data from another joined model (stressz_elegedettseg). The last is the model which I like to get data but it gives me this error: TypeError at /mpa/project_details/by_date/szd-bydate-szervezetielegedettseg/1/1/2022-02-02-2022-05-02 hasattr(): attribute name must be string The Projekt_sz_by_date modell contains a from_date and a to_date that I like to pass trough like this: http://localhost:8000/mpa/project_details/by_date/szd-bydate-szervezetielegedettseg/1/1/2022-02-02-2022-05-02 urls.py path('project_details/by_date/szd-bydate-szervezetielegedettseg/<int:projekt_id>/<int:projekt_bydate_id>/<slug:from_date>-<slug:to_date>', views.szd_by_date_szervezetielegedettseg, name='szd_by_date_szervezetielegedettseg'), views.py def szd_by_date_szervezetielegedettseg(request, projekt_id, projekt_bydate_id, from_date, to_date): projekt = Projekt.objects.raw('SELECT projekt_id, id FROM stressz_profile WHERE stressz_profile.projekt_id=%s', [projekt_id]) from_date = Projekt_szd_by_date.objects.raw('SELECT date_from AS from_date, id FROM stressz_projekt_szd_by_date WHERE stressz_projekt_szd_by_date.id = %s', [projekt_bydate_id]) to_date = Projekt_szd_by_date.objects.raw('SELECT date_to AS to_date, id FROM stressz_projekt_szd_by_date WHERE stressz_projekt_szd_by_date.id = %s', [projekt_bydate_id]) projekt_by_date = Projekt_szd_by_date.objects.raw('SELECT * FROM stressz_projekt_szd_by_date INNER JOIN stressz_projekt ON stressz_projekt.id = stressz_projekt_szd_by_date.id INNER JOIN stressz_elegedettseg WHERE stressz_elegedettseg.date BETWEEN "%s" AND "%s" AND stressz_projekt_szd_by_date.id=%s', [from_date], [to_date], [projekt_bydate_id]) context = { 'projekt': projekt, 'projekt_by_date': projekt_by_date, 'from_date': from_date, 'to_date': to_date, } return render(request, 'stressz/szd-bydate-szervezetielegedettseg.html', context) models.py class Projekt_szd_by_date(models.Model): def __str__(self): return str(self.projekt_szd) projekt_szd = models.CharField(max_length=250) projekt_parent = models.ForeignKey('Projekt', on_delete=models.CASCADE) company_name = models.ForeignKey('Company', on_delete=models.CASCADE) jogosult_01 = models.ForeignKey(User, on_delete=models.CASCADE) date_from = models.DateField(editable=True) date_to = … -
iOS can't play uploaded audio: JS MediaRecorder -> Blob -> Django Server -> AWS s3 -> JS decodeAudioData --> "EncodingError: Decoding Failed"
I am using Javascript MediaRecorder, Django, AWS s3 and Javascript Web Audio API to record audio files for users to share voice notes with one another. I've seen disbursed answers online about how to record and upload audio data and the issues with Safari/iOS but thought this could be a thread to bring it together and confront some of these issues. Javascript: mediaRecorder = new MediaRecorder(stream); mediaRecorder.onstop = function (e) { var blob = new Blob( chunks, { type:"audio/mp3", } ); var formdata = new FormData(); formdata.append('recording', blob) var resp = await fetch(url, { // Your POST endpoint method: 'POST', mode: 'same-origin', headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrf_token, }, body: formdata, }) } Django: for k,file in request.FILES.items(): sub_path = "recordings/audio.mp3" meta_data = {"ContentType":"audio/mp3"} s3.upload_fileobj(file, S3_BUCKET_NAME, sub_path,ExtraArgs=meta_data) ###then some code to save the s3 URL to my database for future retrieval Javascript: var audio_context = new AudioContext(); document.addEventListener("#play-audio","click", function(e) { var url = "https://docplat-bucket.s3.eu-west-3.amazonaws.com/recordings/audio.mp3" var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; request.onload = function () { audio_context.decodeAudioData(request.response, function (buffer) { playSound(buffer) }); } request.send(); }) Results in: "EncodingError: Decoding Failed" Note however that using the w3 schools demo mp3 url does play the recording: …