Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django -> 'WSGIRequest' object has no attribute 'data' -> Error in json.loads(request.data)
I saw a similar question but the answer is rather vague. I created a function based view for updateItem. I am trying to get json data to load based on my request. but am getting the error -> object has no attribute 'data' Views.py file: def updateItem(request): data = json.loads(request.data) productId = data['productId'] action = data['action'] print("productID", productId, "action", action) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer,complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse("Item was added!", safe=False) JS File: function updateUserOrder(productId, action) { console.log('User is logged in...'); let url = '/update_item/'; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ productId: productId, action: action }), }) .then((res) => { return res.json(); }) .then((data) => { console.log('data', data); }); } urls python file: urlpatterns = [ path("",views.store,name="store"), path("cart/",views.cart,name="cart"), path("checkout/",views.checkout,name="checkout"), path("update_item/",views.updateItem,name="update_item"), ] The Error seems to also occur in my fetch function in the JS file. With my method POST. Can't find a solution, what am I doing wrong here? -
Django Rest hash existing non hashed passwords
I have an existing database with non hashed plain text passwords which I want to convert to hashed passwords in Django Rest Framework. I have tried the following but it is not working, as in while the hashing is done I am unable to login when this password is hashed Try 1 queryset = CustomUser.objects.all() for item in queryset: item.password = make_password(item.password) item.save() return Response({"message": "done"}) Try 2 queryset = CustomUser.objects.all() for item in queryset: item.set_password(item.password) item.save() return Response({"message": "done"}) -
Multiple Image upload in django rest framework
How to upload multiple images in DRF. I'm getting all the list of images while looping through it, but it only saves the last one. I want to save all the image and show it in response. Do I have to create separate serializer for Multiple Image serialization? #models class ReviewRatings(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)]) created_at = models.DateField(auto_now_add=True) review = models.CharField(max_length=500, null=True) updated_at = models.DateField(auto_now=True) def __str__(self): return self.product.product_name class ReviewImages(models.Model): review = models.ForeignKey(ReviewRatings, on_delete=models.CASCADE, related_name='review_images', null=True, blank=True) images = models.ImageField(upload_to='reviews/review-images', null=True, blank=True) def __str__(self): return str(self.images) #Serilaizer class ReviewImagesSerializer(ModelSerializer): class Meta: model = ReviewImages fields = ["images"] class ReviewSerializer(ModelSerializer): user = SerializerMethodField() review_images = ReviewImagesSerializer(many=True) class Meta: model = ReviewRatings fields = [ "user", "rating", "review", "created_at", "updated_at", "review_images", ] def get_user(self, obj): return f"{obj.user.first_name} {obj.user.last_name}" #Views class SubmitReview(APIView): permission_classes = [IsAuthenticated] def post(self, request, product_slug): data = request.data if data["rating"] == "" and data["review"] == "": review = ReviewRatings.objects.create( user=request.user, product=product, rating=data["rating"], review=data["review"], ) review_images =request.FILES.getlist('review_images') rev = ReviewImages() for image in review_images: rev.review=review rev.images = image rev.save() serializer = ReviewSerializer(review, context={'request':request}) return Response(serializer.data, status=status.HTTP_201_CREATED) #Postman Response I get on the current implementation { "user": "Jackson Patrick Gomez", "rating": 4.8, … -
How to send the content of html to another html
I would like to fill out a form on an html page and then send the completed form to another html to check the entries there and then save them. I just don't know how to send the data from one html to another. I ask you to help me. Thanks question.html here is the form {% extends 'dependencies.html' %} {% block content %} <div class="jumbotron container row"> <div class="col-md-6"> <h1>Add Question</h1> <div class="card card-body"> <form action="" method="POST" id="form"> {% csrf_token %} {{form.as_p}} <br> <input type="submit" name="Submit"> </form> </div> </div> </div> {% endblock %} approve_questions.html I wanna to get the content from question.html here currently empty views.py def questions(request): form = addQuestionform() if (request.method == 'POST'): form = addQuestionform(request.POST) if (form.is_valid()): form.save(commit=False) html = render_to_string("notification_email.html") send_mail('The contact form subject', 'This is the message', 'noreply@codewithstein.com', ['example@gmail.com'], html_message=html) return redirect("login") context = {'form': form} return render(request, 'addQuestion.html', context) def approve_questions(request): return render(request, "approve_question.html") -
django rest_framework when creating object says get() returned more than one Request -- it returned 2
I'm creating a api where everytime someone request for repairs it also saves in inspection table when I try to post in postman { "reqdescription": "test", "techofficeid": "ICT" } this is the row of request |reqid|reqdescription|reqdate|officerequestor|techofficeid| | 36 | test |2022...| HR | ICT | while this is the row of inspection |inspectid|reqid| etc...| description | | 5 | 36 |.......|Request object (36)| instead of test why it's Request object (36) this is my signals.py @receiver(post_save, sender=Request) def create_transaction_log(sender, instance, created, **kwargs): if created: Inspection.objects.create(reqid=Request.objects.get(reqid=instance.reqid), description=Request.objects.get(reqdescription=instance.reqdescription), reqdate=str(datetime.now().strftime('%Y-%m-%d'))) my assumptions is because of OneToOneField but maybe I was wrong Hope someone can help models.py class Inspection(models.Model): inspectid = models.AutoField(primary_key=True) reqid = models.OneToOneField('Request', models.DO_NOTHING, db_column='reqid', blank=True, null=True) insdate = models.DateField(blank=True, null=True) diagnosis = models.CharField(max_length=100, blank=True, null=True) inspector = models.ForeignKey('Technician', models.DO_NOTHING, db_column='inspector', blank=True, null=True) isinspected = models.BooleanField(default='False', blank=True, null=True) description = models.CharField(max_length=100, blank=True, null=True) reqdate = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'inspection' class Request(models.Model): reqid = models.AutoField(primary_key=True) reqdescription = models.CharField(max_length=100, blank=True, null=True) reqdate = models.DateField(auto_now_add = True, blank=True, null=True) officerequestor = models.ForeignKey('Office', models.DO_NOTHING, db_column='officerequestor', blank=True, null=True) techofficeid = models.ForeignKey('Technicianoffice', models.DO_NOTHING, db_column='techofficeid', blank=True, null=True) class Meta: managed = False db_table = 'request' -
Using Ajax to pass a variable to django views.py
I am trying to use ajax pass a variable "arr" from my calender.html to my views.py file. For testing purposes, I'm returning a HttpResponse for whatever "arr" is. In this case, it is "1" however instead of passing "1", I'm getting "None". I'm unsure of why nothing is being sent. calender.html This is what I have for my calendar function in views.py Output This is what I have for my url.py if its relevant at all I'm pretty new to ajax and still learning Django so if anyone can help, I would really appreciate it. (btw I know calendar is spelled wrong, it wasn't my doing) -
Mass updating (including removal) of a many-to-many relationship django
I have a Django app with two models linked by a many-to-many relationship. Service, problem_type. A service provides assistance for a number of problem types. I use the problem_type table to later facilitate lookups of all services that help for a specific problem type. I update my model from an external API. I take in a list of "problem_types" for each service, eg: ['housing', 'financial aid' ... etc] Over time, a service might get new problem_types or remove old ones. Is there a best practice for managing this? Adding new problem_types relationships or new problem_types is ok, I just loop through the incoming list of problem types and add any new ones to the problem_type relationship/table, but what is the best way to remove now redundant ones? Is it best to: Loop through associated problem types and delete each not in the new incoming list? Get all associated problem types and delete every relationship before re-adding the incoming list Is there some built-in method for doing this that I have not been able to find? In an ideal world love to be able to pass the incoming list of new problem_types with the current set of related problem_types to a … -
import environ could not be resolved pylance when using venv
I'm new in Python/Django and I'm trying to create a live app. I did create the django project first, then realized I should do this in a venv. So I created the venv within my project folder. I managed to get my PostgresQL db connected, and since I'm trying to keep my stuff secure, I'm storing my DB password in a global variable. import environ from pathlib import Path env = environ.Env() environ.Env.read_env() My problem is that I keep getting the error "import environ could not be resolved pylance" in my settings.py file and I've no idea why. I think I've set up my venv correctly and placed it in my project folder. Is something wrong with my interpreter? I'd really like some help with this please. this is how my files are laid out [this is the error i'm seeingI seem to be inside my venv and i'm able to run my app just fine and update my database no problems. which I'm thinking shouldn't work if there really is an issue with how my venv is setup?](https://i.stack.imgur.com/lk2Dn.png) I've tried everything I can think of. Made another venv and played around with it. Only thing I'm stuck on is … -
Django: Selenium multiple drivers (windows)
I'm creating API that is based on web-scraping via Selenium. And I've just figured out that: if user1 makes request, as long as he's waiting for response (selenium is scraping page for needed data) user2 must wait for user's1 chromedriver to stop session and only after that selenium starts scraping data for user2, that's not efficient at all ;(I'm pretty sure it's possible to run multiple drivers at the same time (one driver for each request) just like Django-channels run multiple channels. How can I achieve that? I'M NOT TESTING, I'M SCRAPING WEB-PAGES -
DRF Nested serializers
I'm kind of confused in writing the nested serializer in django rest framework. If I have tow models Account and UserProfile. In which UserProfile is ForeignKey to Account and when writing serilaizer should I call UserProfile Serializer in Account's Serializer or call Account Serilaizer in UserProfile Serializer. #Models.py Class Account (AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True Class USerProfile(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) address_line_1 = models.CharField(max_length=100) address_line_2 = models.CharField(max_length=100) phone = models.IntegerField(null=True) And in writing serializer I'm confused. So please explain to me in detail how to write nested serializer. #Serializers.py class AccountSerializer(ModelSerializer): class Meta: model = Account fields = ["first_name", "last_name", "email", "password"] extra_kwargs = { "password": {"write_only": True}, } class UserProfileSerializer(ModelSerializer): user = AccountSerializer() class Meta: model = UserProfile fields = "__all__" def create(self, validated_data): #Didn't write the logics here as of now. return super().create(validated_data) So Is this this correct way to write nested serializer? -
process 'forkPoolworker-5' pid:111 exited with 'signal 9 (SIGKILL)'
hello every one who helps me? python:3.8 Django==4.0.4 celery==5.2.1 I am using python/Django/celery to do something,when I get data from hive by sql,my celely worker get this error "process 'forkPoolworker-5' pid:111 exited with 'signal 9 (SIGKILL)'",and then,my task is not be used to finish and the tcp connect is closing! what can I do for it to solve? I try to do: CELERYD_MAX_TASKS_PER_CHILD = 1 # 单work最多任务使用数 CELERYD_CONCURRENCY = 3 # 单worker最大并发数 CELERYD_MAX_MEMORY_PER_CHILD = 1024*1024*2 # 单任务可占用2G内存 CELERY_TASK_RESULT_EXPIRES = 60 * 60 * 24 * 3 -Ofair but these is not using for solving. -
Function trigger other function and ends before result
I'm developing an API with Django Rest Framework for handling some subscriptions I wanted do make the registration in 2 steps. First, i would register user in my database, after that i want to register user to other service (email marketing, for example). I have to do it in two steps because the registering of the user in external services may take some time (or the service can be unavailable at the time of request) and i don't want users to wait everything so they can go to other pages. My idea is: After registering user into my database, i would return http 200_ok to the front-end so user can go to other pages, and in my backend i would use that data to try to register the user in external services as many times as needed (e.g: waiting if other services are unavailable). But rest_framework only allows me to return Response() (i'm using class-based views), so i only can return http 200_ok, but if i return the function ends and my other functions (that will take more time to run) will end aswell. Is there a way to do this? -
Django Multiprocessing Error on Server But Works Fine on Localhost - __init__() got an unexpected keyword argument 'initializer'
When I Run my Django App on my computer it works fine. But when pushed to Ubuntu Server I am now getting the error. __init__() got an unexpected keyword argument 'initializer' Here is my View Code def verifyt(request): listi = get_listi() print("verifyt",listi) with ProcessPoolExecutor(max_workers=4, initializer=django.setup) as executor: results = executor.map(wallet_verify, listi) return HttpResponse("done") Ive upgraded my python from 3.6.9 to 3.7.5 still same error. -
I want to add 'created_by' and 'modified_by' fields to my Django models, How do I do that?
My custom user model in account.models.py: class MyRegistration(AbstractBaseUser, PermissionsMixin): location_list=[ ('abc', 'abc'), ('def', 'def'), ] username=models.CharField(max_length=10, unique=True) email=models.EmailField(unique=True) first_name=models.CharField(max_length=150) last_name=models.CharField(max_length=150) location=models.CharField(max_length=10, choices=location_list, default=None) designation=models.CharField(max_length=70) is_active=models.BooleanField() is_staff=models.BooleanField(default=False) start_date=models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(null=True) USERNAME_FIELD='username' REQUIRED_FIELDS=['email', 'first_name', 'last_name', 'location', 'designation'] objects=FirstManager() def __str__(self): return self.username A model in sample.models.py: class LockData(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE, default=None) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None, blank=True, null=True) lock=models.BooleanField(default=False) date=models.DateField(default=datetime.date.today) created_on=models.DateTimeField(auto_now_add=True) modified_on=models.DateTimeField(auto_now=True) So, along with created_on and modified_on fields, I also want 'created_by' and 'modified_by' fields. How can I do that? -
django path issue with filebrowser in tinymce
When inserting an image through tinymce in django, there is a problem with the src path of the img. The media is browsed through filebrowser and the image is inserted into tinymce, but the image path is <img src="../../../../media/path/to/img.file"> instead of a url. to be designated How can I make that path a full url path <img src="/media/path/to/img.file">? I tried applying the following settings in settings.py but it doesn't work. Django Tiny_MCE and FileBrowser leading ../../../ TINYMCE_DEFAULT_CONFIG = { 'remove_script_host' : 'false', 'convert_urls' : 'false', } -
Prevent error when missing key in Django Rest Framework
I'm building an API for handling database and email-marketing data for other websites of mine. I have an endpoint for deleting users from database and ActiveCampaign, to prevent making any delete requests by mistake, i'm checking if there's a key:value pair in the request body, if 'delete': true, proceed, if not, i want to return an error message with status code for letting me (or other that i may include in project in the future) know what was the mistake. My is: While checking if there is a key named 'delete' i get an error and my program stop working. I wish to know if there's a way of only "doing stuff" after some checking, but without breaking my program, if something not expected would happen, it would send an error back to request origin. Here's the class/function i'm trying to make work: class Leads(APIView): @staticmethod def delete(request): if request.data["delete"]: delete_from_db = Lead.objects.filter(email=request.data["email"]) lead = LeadHelper(email=request.data["email"] if request.data["email"] else "") lead.delete_from_activecampaign() return Response([delete_from_db], status=status.HTTP_200_OK) else: payload = { "message": "Denied because 'delete': 'true' was not found in request, did you sent this by error?" } return Response(payload, status=status.HTTP_401_UNAUTHORIZED) My main problem is that if there's no 'delete' key, it don't … -
django - having trouble selecting values based on FK relationship in views.py
I have two models that look like; class Body(models.Model): body_id = models.AutoField(primary_key=True) is_adult = models.BooleanField(default=False) body = models.TextField() add_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) add_date = models.DateTimeField() edit_user = models.CharField(max_length=25, blank=True, null=True) edit_date = models.DateTimeField(blank=True, null=True) category = models.ForeignKey(Category, models.CASCADE) class Meta: managed = True db_table = 'jdb_body' class BodyTag(models.Model): body_tag_id = models.AutoField(primary_key=True) body = models.ForeignKey('Body', models.CASCADE) tag = models.ForeignKey('Tag', models.CASCADE, db_column='tag') class Meta: managed = True db_table = 'jdb_body_tag' def __str__(self): return self.tag I have a view that looks like; def index(request): latest_body_list = Body.objects.all().order_by('-body_id') context = { 'latest_body_list': latest_body_list } return render(request, 'index.html', context) That view gives me a list Body records no problem. I am trying to display Body records with their corresponding BodyTag records. What am I doing wrong? -
Import project's subpackages in Python
i'm experimenting with DDD in Python so i've decided to implement a toy project. I've created different directories in other to separate shared concepts from specific bounded contexts concepts. As i try to import these files, i'm facing a No module named error exceptions For example, with this project structure: . └── src/ ├── Book/ │ ├── application │ ├── domain/ │ │ ├── Book.py │ │ └── __init__.py │ ├── infrastructure │ └── __init__.py └── Shared/ ├── application ├── domain/ │ ├── Properties/ │ │ ├── __init__.py │ │ └── UuidProperty.py │ ├── ValueObjects/ │ │ ├── __init__.py │ │ └── BookId.py │ └── __init__.py └── infrastructure On src/Book/domain/Book.py i have: from Shared.domain.ValueObjects.BookId import BookId class Book: bookId: BookId pages: int As i've seen in other answer (pretty old ones) it can be fixed by adding these folders to PYTHONPATH or PATH like sys.path.insert(*path to file*) but i'm wondering if there is a more pythonic way to achieve that. I've also tried to add an __init__.py file to src and import as from src.Shared.domain.ValueObjects.BookId import BookId but none of previous attempts worked for me On other repos i've saw that they use setuptools to install the src package in … -
Fail to pass/use string argument for img to html file in Django app?
I am very new to Django and was trying to pass one argument as a string to my html file so that I can call to use my image. I have the below code to call static image: {% load static %} <img src= "{{ user_age_pic_name }}" width=950 height=450px padding = 40px alt="" > However, this is not working (I also tried deleting the double quote). I know the image is correct because when I call <img src= "{% static 'research/used_viz/comparative/age/12-15.jpg' %}" width=950 height=450px padding = 40px alt="" > The img works perfectly. I also try to just print out the text and it seems to work fine. I think it should be cause by limited understanding of HTML arguments. Could someone guide me through this? Any input is appreciated! -
how to dynamically set the choices of a choice field in django DRF serializer through __init__ or __new__ method?
I am trying to dynamically set the choices of a choice field in django serializer class I want to pass the choices (dynamically) to it and it set it for me The simplified version of the project is this # urls urlpatterns = [ path("cat", CatView.as_view(), name="cat") ] I have tried different things and they don't work. I am sharing one of them here I even had to use the private methods (which I would prefer not to) of the field but still not successful # serializers class CatSerializer(serializers.Serializer): name = serializers.ChoiceField(choices=[]) def __new__(cls, *args, **kwargs): name_choices = kwargs["names"] f = CatSerializer._declared_fields["name"] f._set_choices(name_choices) f.__dict__["_kwargs"]["choices"] = name_choices obj = super().__new__(cls) return obj def __init__(self, *args, **kwargs): kwargs.pop("names") super().__init__(self, *args, **kwargs) # views class CatView(APIView): def __init__(self, *arg, **kwargs): super().__init__(*arg, **kwargs) self.names = ['a', 'b', 'c'] def get_serializer(self, *args, **kwargs): serializer_class = CatSerializer return serializer_class( *args, **kwargs, names=self.names ) def post(self, request): request_body = request.body serializer = self.get_serializer( data=json.loads(request_body), ) is_data_valid = serializer.is_valid() if is_data_valid: serialized_data = serializer.data return Response({"message": "success", "serialized-data": serialized_data}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I now see this error: AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `CatSerializer`. The serializer field might be … -
Sum using Django Template syntax?
I have an exercise that consists of sets, I assign sets to this exercise model. I am able to calculate the total volume of a single set. But how do I calculate the total volume for the exercise. Is it possible to return the sum value of a for loop? When I do it in the view I am only able to return the sum of .all() like this def homeview(request): set = ExerciseSetModel.objects.all() sum = 0 for obj in set: sum += obj.setvolume() context = { 'sum': sum, # returns the sum of everything but I want the single exercise } return TemplateResponse(request, 'poststemplates/posthome.html', context) model: class ExerciseModel(models.Post): exercisename = models.TextField(max_length=500, verbose_name='text', blank=True, null=True, default="text") class ExerciseSetModel(models.Post): exercise = models.ForeignKey(ExerciseModel, on_delete=models.CASCADE, default=None,) repsnumber = models.IntegerField(default=1, null=True, blank=True) weightnumber = models.IntegerField(default=1, null=True, blank=True) def setvolume(self): return self.repsnumber * self.weightnumber views: @login_required def homeview(request): exercises = ExerciseModel.objects.all() context = { 'exercises': exercises, } return TemplateResponse(request, 'poststemplates/posthome.html', context) template: {% for exercise in exercises %} {% for set in exercise.exercisesetmodel_set.all %} {{set.setvolume}} {% endfor %} {% endfor %} now let's say that I have two sets inside a single exercise, I'm able to calculate the set volume for each set, but how … -
How to properly render form fields with django?
I am currently working on a login page for a django webapp. I am trying to include the login form within the index.html file. However, the form fields are not being rendered. My urls are correct I believe but I'm not sure where I am going wrong. Here is my views.py, forms.py and a snippet of the index.html. (I do not want to create a new page for the login I'd like to keep it on the index page) # Home view def index(request): form = LoginForm() if form.is_valid(): user = authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password'], ) if user is not None: login(request, user) messages.success(request, f' welcome {user} !!') return redirect('index_logged_in.html') else: messages.info(request, f'Password or Username is wrong. Please try again.') return render(request, "index_logged_out.html") class LoginForm(forms.Form): username = forms.CharField(max_length=63) password = forms.CharField(max_length=63, widget=forms.PasswordInput) <!-- Login --> <section class="page-section" id="login"> <div class="container"> <div class="text-center"> <h2 class="section-heading text-uppercase">Login</h2> </div> <form> {% csrf_token %} {{form}} <center><button class="btn btn-primary btn-block fa-lg gradient-custom-2 mb-3" type="submit" style="width: 300px;">Login</button></center> </form> <div class="text-center pt-1 mb-5 pb-1"> <center><a class="text-muted" href="#!">Forgot password?</a></center> </div> <div class="d-flex align-items-center justify-content-center pb-4"> <p class="mb-0 me-2">Don't have an account?</p> <button type="button" class="btn btn-outline-primary"><a href="{% url 'register' %}">Create New</a></button> </div> </form> </div> </section> -
ExcelResponse doesn't send file correctly
I'm using django-excel-response 2.0.5 to download Excel sheet using Django. sheet = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6], [7, 8, 9]] response = ExcelResponse(sheet, 'test') return response Instead of downloading file, it doesn't open anything and response.data is byte version of file, like PK�����5���� ��GEp,���L�v��>�ݾ��cb�x����Ш=���0����E &o��PK Is there a problem in Django rest settings, or I'm using lib wrong? I tried to change view class, different response classes, but nothing helped -
Integrating Vite (VueJs) frontend with Django Login Form
I am looking to understand how once it is checked that a user is authenticated using a django login form, how they can then be taken to a vue frontend made using vite? Many examples I have seen make use of webpack loader however, I am using vite. I am developing locally, so is it a matter of just directing the user to a local server url only if authenticated? The idea is depending on the authenticated user, certain information will need to be gathered associated with them. -
How to send audio file from front end to django backend through websockets for processing at the backend
I have made a website in django that uses websockets to perform certain tasks as follows : From frontend I want to take audio using MediaRecorder as input api through javascript I want to send this audio back to the backend for processing and that processed data is again send back through the connection in realtime. I have tried various things for the purpose but haven't been successful yet. The bytes data that I've been receiving at the backend when I'm converting that into audio then I'm getting the length and size of the audio file but not getting the content of the file. Means the whole audio is silent but the same audio which I'm listening in the frontend is having some sound. but I don't know what's happening at the backend with the file. Consumer.py : import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["username"] self.room_group_name = "realtime_%s" % self.room_name self.channel_layer.group_add( self.room_group_name, self.channel_name) await self.accept() print("Connected") async def disconnect(self , close_code): await self.channel_layer.group_discard( self.roomGroupName , self.channel_layer ) print("Disconnected") async def receive(self, bytes_data): with open('myfile.wav', mode='bx') as f: f.write(bytes_data) audio.js : <script> navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => { if (!MediaRecorder.isTypeSupported('audio/webm')) return alert('Browser not supported') …