Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can i use sqlite3 for simple django blog application in production?
After hours of watching tutorials and reviewing the documentations of django and heroku, i finally deployed my simple django web application. For the database part, i came to know about an issue using sqlite database as default database for production. I fear that i lose my records after deploying the application once done, as said by heroku themselves. I am currently having one user, who post posts and announcements in the website and public viewers can only view it. My question is, is it correct to use sqlite database for production or will the free postgres database be enough for what i am doing with? -
Unable to connect to server: PgAdmin 4
I have installed pgadmin on a new laptop and when I try to create a new server, it says: When I try to run my django app in pycharm it is giving me the same error could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? How to solve this ? -
Django: Email being sent as html for password reset
The email sent for resetting password are being displayed as raw HTML content. This is not the case for every users but for significant number of users, this problem arrives. This is my url for password reset: from django.contrib.auth.views import password_reset url(r'^accounts/password/reset/', password_reset, {'template_name':'users/login.html','html_email_template_name':'registration/password_reset_email.html', 'post_reset_redirect':'/users/accounts/login/?reset=1', 'extra_context':{'reset':'1'}}, name='password_reset'), These are my password reset email templates: registration/password_reset_email.html {% extends 'users/email_base.html' %} {% block content %} {% load i18n %} <table width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#f0f0f0" align="center"> <tbody> <tr> <td style="font-size:0;" align="center"> <div style="display:inline-block;width:100%;max-width:800px;vertical-align:top;" class="width800 mrt-30"> <!-- ID:BG SECTION-1 --> <table class="display-width" style="max-width:800px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#ffffff" align="center"> <tbody> <tr> <td class="padding" align="center"> <div style="display:inline-block;width:100%;max-width:600px;vertical-align:top;font-family:Ubuntu, sans-serif;" class="main-width"> <table class="display-width-inner" style="max-width:600px;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"> <tbody> <tr> <td style="mso-line-height-rule:exactly;line-height:30px;font-size:0;" height="30"> </td> </tr> <tr> <td style="mso-line-height-rule:exactly;line-height:10px;font-size:0;" height="10"> </td> </tr> <tr> <td style="color:#666666;font-family:Ubuntu, sans-serif;font-weight:400;font-size:14px;line-height:24px; text-align:justify;"> {% blocktrans %} You're receiving this email because you requested a password reset for your user account at {{ site_name }}. {% endblocktrans %} </td> </tr> <tr> <td style="color:#666666;font-family:Ubuntu, sans-serif;font-weight:400;font-size:14px;line-height:24px; text-align:justify;"> Please go to the following page and choose a new password: {% block reset_link %} https://{{ domain }}{% url 'auth_password_reset_confirm' uidb64=uid token=token %} {% endblock %} Your username, in case you've forgotten: {{ user.get_username }} </td> </tr> <tr> … -
JS send html with django tags
I am cretaing widget in JS. And I want to send html through jquery.html() method. But I am using also django trans tag. This is my after cretating widget code on html side: <div class="modal-header" style="padding: 5px;padding-left: 25px;"> <h5 class="modal-title" id="componentName">{% trans "Report" %}</h5> </div> And this is my code on JS side html = '<div class="modal-header" style="padding: 5px;padding-left: 25px;">'+ '<h5 class="modal-title" id="'+IdCreateHelper(component_names[i])+'">'+'{% trans "'+component_names[i]+'" %}'+'</h5>'+ '</div>' $('#'+modal_id).html(html); I want to create django tags on JS side but result is: {% trans "Reports" %} <h5 class="modal-title" id="componentName">{% trans "Report" %}</h5> I want to create django tags in js -
Redirect to another url in django admin
I have this default configuration of django admin url. I have another unique identifier field in my model. What I want to achieve is to allow to redirect http://localhost:8000/admin/cart/uniq_identifier/change to http://localhost:8000/admin/cart/cart_id/change A clear example would be http://localhost:8000/admin/cart/1ASFFX24/change will be redirected to http://localhost:8000/admin/cart/1/change -
URL Structuring in Django 2.2
I am using Django 2.2 I am having an app called shop inside the main site. All the categories and products are available as Case1: http://localhost:8000/shop/<category-name> http://localhost:8000/shop/<category-name>/<product-name> However I want to achieve this case 2: http://localhost:8000/<category-name> http://localhost:8000/<product-name> ie. from base I want to be able to call the functions of the app. ie the case 2 urls should work instead of case1 . What is the best way to achieve this using urls.py This my urls.py inside shop app path('',views.allProdCat,name='allProdCat'), path('<slug:c_slug>/', views.allProdCat, name='products_by_category'), path('<slug:c_slug>/<slug:product_slug>/', views.ProdCatDetail, name='Prod'), This is in urls.py in base project urlpatterns = [ path('admin/', admin.site.urls), path('',views.index, name='index'), path('shop/',include('shop.urls')), ] -
Pytest-django dependency injection
How does pytest-django know whether to inject a test function with a RequestFactory or Client instance? def test_with_client(client): response = client.get('/') assert response.content == 'Foobar' def test_details(rf): request = rf.get('/customer/details') response = my_view(request) assert response.status_code == 200 how can you be certain that test_with_details takes a RequestFactory? -
how can I put the comment show on form
I have to let the "comment" show in the report_detail.html this is django 2.2 , I have try add views.py some code but fail, the Report need to show the comment below, however, I try add some code in views.py and report_detail.html but it can not work, how can I do ? thank you models.py class Report(models.Model): done = models.TextField('what done') willDo = models.TextField('will do') date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.done def get_absolute_url(self): return reverse('report_detail', args=[str(self.id)]) class Comment(models.Model): report = models.ForeignKey( Report, on_delete=models.CASCADE, related_name='comments', ) comment = models.CharField(max_length=140) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.comment def get_absolute_url(self): return reverse('report_list') views.py class ReportDetailView(LoginRequiredMixin, DetailView): model = Report template_name = 'report_detail.html' login_url = 'login' report_detail.html <div class="article-entry"> <h2>{{ object.done }}</h2> <p>by {{ object.author }} | {{ object.date }}</p> <p>{{ object.willDo }}</p> </div> -
How to loop through urls in a template
I have a load of URLs I want to declare as constants so I can use them in if statements in a template. At the moment I do this manually e.g.: {% url 'inbox' as inbox %} {% url 'sent' as sent %} {% url 'drafts_tasks' as drafts_tasks %} However this feels kinda clunky and when the urls increase in numbers it is a load of extra code repeated on every template. Is there a better way I can loop through urls and declare them? -
How to solve OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect error in pycharm
I'm a new at django and immediately i try to edit the web application and run the server I get the error message above on my terminal, please help Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\W\PycharmProjects\manuproject\venv\lib\site- packages\django\core\manageme nt\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\W\PycharmProjects\manuproject\venv\lib\site- packages\django\core\manageme nt\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\W\PycharmProjects\manuproject\venv\lib\site- packages\django\core\manageme nt\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\W return self._accessor.stat(self) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' I expect the output Hello World on my web application page -
Get or create in Django Rest framework
I want to have get_or_create funcionality when posting data to a model with foreign keys. None of the solutions I found had worked. I've tried to override create method. My Models: class Branch(models.Model): branch_name = models.CharField(max_length=30, primary_key=True) class Developer(models.Model): login = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=30) email = models.EmailField() class Commit(models.Model): commit_id = models.CharField(max_length=40, primary_key=True) author = models.ForeignKey(Developer, on_delete=models.CASCADE) branch = models.ForeignKey(Branch, on_delete=models.CASCADE) My serializers: class BranchSerializer(serializers.ModelSerializer): class Meta: model = Branch fields = '__all__' class CommitSerializer(serializers.ModelSerializer): branch = BranchSerializer() author = DeveloperSerializer() class Meta: model = Commit fields = '__all__' def create(self, validated_data): branch_data = validated_data.pop('branch') author_data = validated_data.pop('author') branch, _ = Branch.objects.get_or_create(**branch_data) author, _ = Developer.objects.get_or_create(**author_data) return Commit.objects.create(branch=branch, author=author, **validated_data) This works if none of the models instances exists in the database. However my solution fails if I try to post new commit to existing branch or using existing developer. Django Rest framework is responding with bad request message. -
django docker container cannot access redis container when using redis as session backend
I am trying to deploy staging enviroment that mimics my django+postgresql(AWS RDS)+redis(AWS Elasticache). I use the latest django-redis(4.10) to set up django with redis. My settings are as follows: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", # Mimicing memcache behavior. # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior "IGNORE_EXCEPTIONS": True, }, } } # django-redis: use redis as session cache SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" When I run this locally in my pipenv enviroment with postgresql running remotely on AWS RDS & redis server running locally on brew services, everything works fine. But if I docker-compose up the containers, django's session handling seems to break. My docker-compose as follows: version: '3.7' services: django: &django restart: always build: context: . dockerfile: ./compose/staging/django/Dockerfile image: staging_django container_name: staging_django hostname: staging_django networks: - backend env_file: - ./.envs/.staging/.django command: /start nginx: build: context: . dockerfile: ./compose/staging/nginx/Dockerfile image: staging_nginx container_name: staging_nginx hostname: nginx ports: - "80:80" networks: - backend restart: on-failure links: - django depends_on: - django networks: backend: driver: 'bridge' When I try to login to admin site, django container returns following errors. staging_django | File "/usr/local/lib/python3.7/site-packages/django/contrib/sessions/backends/cache.py", line 51, in create staging_django | "Unable to create a new session key. " staging_django | RuntimeError: … -
Changing the way of showing how are records showed in database
I am trying to create web app on tracking orders. I have problem with the way how is showed assigning orders to my users. If I add a lot of users to the database the roll down menu is not very good looking and it takes long time to find out the correct user. Is there any way to change the roll down menu to the searching bar which will find user based on the string input? Here is my models.py where I created MyUser and Order. class MyUser(models.Model): id = models.CharField(max_length=7) first_name= models.CharField(max_length=50) second_name = models.CharField(max_length=50) class Objednavka(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE) order = models.CharField(max_length=11) views.py class CreateOrder(generic.edit.CreateView): form_class = OrderForm template_name = "url.html" def get(self, request): form = self.form_class(None) return render(request, self.template_name, {"form": form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): form.save(commit=True) messages.success(request, f'Order has been created successfully') return render(request, self.template_name, {"form": form}) -
Import data with relationships using django-import-export
I have three models and I'd like to import data into them using django-import-export but I can't figure out how to do the relationships. I have two csv files, one containing Assets and the other Options. CSV - Assets name,unique_id car,carXYC, car2,carABC, CSV - Options name,unique_id stereo,carXYC, tires,carXYC, leather,carXYC, 4wdtires,carABC, pleather,carABC, models.py class Option(models.Model): name = models.CharField( max_length=255, ) class Asset(models.Model): name = models.CharField( max_length=255, ) unique_id = models.CharField( max_length=255, unique=True, ) option = models.ManyToManyField( Option, through=AssetOptionsThrough, ) class AssetOptionsThrough(models.Model): asset = models.ForeignKey( "Asset", on_delete=models.CASCADE, ) option = models.ForeignKey( "Option", on_delete=models.CASCADE, ) resources.py class AssetResource(resources.ModelResource): class Meta: model = Asset fields = ('name', 'unique_id',) class OptionResource(resources.ModelResource): unique_id = fields.Field(column_name='unique_id') class Meta: model = Option fields = ('name', 'unique_id',) unique_id is included in the OptionResource class only so we can then match it to the correct Asset, we don't actually store it in the Option model. From here I would like to: Import Assets CSV (Manual Step via Django Admin) Import Options CSV (Manual Step via Django Admin), which would for each row: a) create the Option record b) use the unique_id to lookup the correct Asset c) create a record linking them in the AssetOptions through model (using result from … -
Django-Rest-Auth: Require another field at registration
I am managing some userdata using Django and I would like to offer those persons them the possibility to take a look at their data by registering and (at once) connecting their accounts to the existing data. I therefore handle them a authentification-token, printed on a sheet of paper, in order to connect their already existing data to their accounts they have to send that token along with their desired username, email, password etc. My Userdata Model looks like this: class Userdata(models.Model): number = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) useraccount = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) auth_token = models.CharField(max_length=12, default="DUMMY", unique=True) Therefore I would like to change the registration process, using djang-rest-auth and allauth to check if there exists a row in the userdata table where the auth_token equals the provided one at the registration. If, then I would like to set the useraccount field in this row to the newly created account, if not, then I would like to raise an error and stop the registration of the account. I am totally lost at the moment and have no idea where to start. I would really appreaciate any hint into the right direction. Thank you! -
Translate html attribute in django project when returning a html element in javascript
I want to dynamically translate a html button title attribute in my django project using _("to be translated") or {% trans "to be translated" %} in a javascript file. The compilation of the .po files for internationalisation works fine for the .html files: <li data-toggle="popover" title="{% trans 'to be translated' %}" In my .js file, I return a HTML element from within a function: return $('<button title="{% trans 'to be translated' %}" type="button" class="gk btn btn-default pull-right"></button>').click(onclick); Due to nested quotes ("{% trans 'to be translated' %}" ) and blanks (_("to be translated")) returning a html element from a .js file including a translation does not seem to work. Is there any workaround for this in django? Thank you! -
Django query assigns database columns to wrong model instance properties
Really weird problem - when I query for a model instance the data comes back assigned to the wrong properties. The model: class SaleLineItem(models.Model): sale = models.ForeignKey(Sale, on_delete=models.CASCADE, related_name="sale_line_items") stock_unit = models.ForeignKey(StockUnit, on_delete=models.CASCADE, related_name="sale_line_items") currency = models.CharField(max_length=3) price_original = models.FloatField() price_paid = models.FloatField() tax_amount = models.FloatField(null=True, blank=True) num_sold = models.IntegerField() sale_line_item_id = models.CharField(max_length=30, null=True, blank=True) status = models.CharField(max_length=20, choices=SALE_STATUS_CHOICES, null=True, blank=True) The database row: id | currency | price_original | price_paid | tax_amount | num_sold | sale_line_item_id | status | sale_id | stock_unit_id -------+----------+----------------+------------+------------+----------+-------------------+-----------+---------+--------------- 15726 | THB | 130 | 130 | | 1 | | delivered | 16219 | 2 And the query: sli = SaleLineItem.objects.get(pk=15726) print(sli.pk) ------------------------- 16219 print(sli.stock_unit_id) ------------------------- THB print(sli.currency) ------------------------- 130.0 The data get populated on the object but everything is "shifted" by one column. But if I do the query this way: SaleLineItem.objects.filter(pk=15726).values() ------------------------- <QuerySet [{'id': 15726, 'sale_id': 16219, 'stock_unit_id': 2, 'currency': 'THB', 'price_original': 130.0, 'price_paid': 130.0, 'tax_amount': None, 'num_sold': 1, 'sale_line_item_id': None, 'status': 'delivered'}]> . . . the result is correct. I thought I might have un-migrated models but I ran both make migrations and migrate to no effect. Any ideas what's happening here? -
Where in my django app do I implement this get_client_ip() function?
I have a Custom User model that takes user ip address. I want to add the IP address of the user upon completion of the sign up form. Where do I implement the below code? I am not sure whether to put this into my forms.py or views.py file. def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip I expect to be able to save the user's ip address into my custom user table upon sign up. -
Django - how to save distinct values in a queryset object?
I have the following Django models: A Proposal which must be unique and Domains that could have the same name in separate Proposals but must be unique to the Proposal object that it belongs to. class Proposal(models.Model): proposal_name = models.CharField( max_length=200, primary_key=True, ) class Category(models.Model): proposal_name = models.ForeignKey( Proposal, on_delete=models.CASCADE, ) category_name = models.CharField( max_length=200, unique=True, ) Currently if I have a Proposal -> Proposal 1, then it could contain Categories-> 'cat A', 'cat B'. But If I have another Proposal -> Proposal 2, then I want this proposal to be able to contain similar category names like 'cat A'.. But since in my Category model, I have given a constraint of unique=True to he category_name, I am unable to store such duplicate category names in a separate proposal. Please guide an alternative for the same, probably a onetoonefield? Thanks. -
Removing query string from a view in Django
I have a page called controlpanel, where I can start/stop scripts. When the button for start and stop scripts is pressed, it return the same page with button color changed and I want to delete query string. view.py def controlpanel(request): data = {'paypal': paypal_, 'cpu': cpu_usage, 'active': active_task ...} return render(request, 'admin/controlpanel.html', context=data) def startapp(request): if request.META['QUERY_STRING']: #... start scripts etc.. request.META['QUERY_STRING'] = False return controlpanel(request) the function return controlpanel with query string... (127.0.0.1:8000/startapp?run=True but I only want 127.0.0.1:8000/controlpanel) controlpanel.html <div> {% if active %} <button onclick="f()" class="btn btn-md btn-success">Start</button> {% else %} <button onclick="f()" class="btn btn-md btn-warning">Start</button> {% endif %} </div> <script> function f() { let a = null; if ('{{active}}' === 'True') { a = 'stop' } else { a = 'start' } window.location.href = "/startapp?run=" + a; } </script> -
Django Python Dropdown failing on submit
Getting errors, when selecting dropdown and hit Go To. It looks like it is not POST value back and thru error. Under View, If I add following it will get to second page, but without passing any value: class GatherDataView(FormView): context_object_name = 'location' template_name = 'gatherdata.html' form_class = SelectSITEForm It doesn't pass the value onclick submit button. forms.py class SelectSITEForm(forms.Form): LOCATIONS = ( ('DC1', 'DC1'), ('DC2', 'DC2'), ) location = forms.ChoiceField(choices=LOCATIONS, required=True) class Meta: model = SelectSITE views.py from .models import SelectSITE from .forms import SelectSITEForm class CheckView(FormView): template_name = "check.html" form_class = SelectSITEForm class GatherDataView(FormView): def gatherdata(request): form = SelectSITEForm(request.POST or None) answer = '' if form.is_valid(): location = form.cleaned_data.get('location') return render(request, 'gatherdata.html', {'form': form, 'location': location}) urls.py urlpatterns = [ url(r'^navbar/', views.NavPageView.as_view()), url(r'^check/', views.checkView.as_view()), url(r'^gatherdata/', views.GatherDataView.as_view(), name='gatherdata'), ] html <form method="post" action = "{% url 'gatherdata' %}"> {% csrf_token %} <div class="fieldWrapper" align="center" id="mainselection"> <select name="location"> <option selected>Select an the site</option> {% for val in form.location %} <option value="{{ val }}"></option> {% endfor %} </select> </div> <button align="center" class="button execute" name="submit" value="submit">GO TO</button></form> onclick submit button HTML {% extends "check.html" %} {% block content %} <br><br><br> <h1>{{ location }}</h1> Traceback: URL: http://dpaste.com/3A0TFDS Exception Type: TypeError at /gatherdata/ Exception … -
null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (fields here)
I am using jwt auth system When I fill the field it returns jwt token easily but if i want to create a profile with this token and it throws folling error IntegrityError at /profile/ null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (7, 2019-07-19 05:38:32.786263+00, 2019-07-19 05:38:32.786305+00, John, Doe, 2017-02-05 05:25:00+00, null, , England,english , native, null). user/models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=40, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' user/views.py class CreateUserAPIView(APIView): permission_classes = (AllowAny,) def post(self, request): user = request.data serializer = UserSerializer(data=user) serializer.is_valid(raise_exception=True) serializer.save() try: email = request.data['email'] password = request.data['password'] user = CustomUser.object.get(email=email, password=password) if user: try: payload = jwt_payload_handler(user) token = jwt.encode(payload, settings.SECRET_KEY) user_details = {} user_details['id'] = "%s" % (user.id) user_details['token'] = token user_logged_in.send(sender=user.__class__, request=request, user=user) return Response(user_details, status=status.HTTP_200_OK) except Exception as e: raise e else: return Response(status=status.HTTP_403_FORBIDDEN) except KeyError: res = {'error': 'please provide a email and a password'} return Response(res) with this code I am getting a token but cannot create a profile for profile creation models.py class Profile(TimeModel): user = models.OneToOneField('user.CustomUser', on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) birthdate = models.DateTimeField(null=True) image … -
TypeError at : / __init__() takes 1 positional argument but 2 were given
i I'm beginner in learning Django, I got this error when i try to runserver: __init__() takes 1 positional argument but 2 were given the urls: from django.contrib import admin from django.urls import path from users import views as user_views from main.views import about, ListView from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('about/', about, name='about'), path('', ListView, name='PostListViews'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) here is my views: from django.shortcuts import render from .models import Post from django.views.generic import ListView def blog(request): context = { 'posts': Post.objects.all() } return render(request=request, template_name='main/blog.html', context=context) class PostListViews(ListView): model = Post template_name = 'main/blog.html' def about(request): return render(request=request, template_name='main/about.html') i don't know where the error comes from please explain to me and Thank you in advance :) -
Django Settings Apps Model
Hi i want to ask what is the meaning of "Config" in intalled_apps in django like this ```python 'polls.apps.pollsConfig' ```` is it okay to put only the name of the apps example 'sample_apps' ? -
sending and receiving files over websockets with additional information
I am trying to develop a chat application on django, for live communication I am using websockets. Messaging is working fine but I am in trouble with files, if any one attach multiples files then how to send and receive it with some additional data. I had set - chatSocket.binaryType = 'arraybuffer'; For simple messaging - chatSocket.send(JSON.stringify( {'id': next_id, 'message': message, 'karma' : karma.val(), 'cert': cert.attr('data'), } )); if someone try to send multiple images then - let files = document.getElementById("attach_img").files; // files.item = '092' console.log('files send requested',files); chatSocket.send(files, { binary: true }); In my consumers.py async def receive(self, text_data=None, bytes_data=None): print('recieved',bytes_data, text_data) It is printing - recieved None [object FileList] but when I change my files as - let files = document.getElementById("attach_img").files['0']; then received bytes_data will be something like- b'\xff\xd8\xff\xe0\x00\x10JFIF\..... I want to send the images + id + cert to server. I search a lot on internet but unable to get the solution how I can send files with additional information over websockets.