Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Receive unexpected token ), on webpack config
I am building a web-application and want to implement webpack in order to run react and django simultaneously. When I attempt to run "webpack --config webpack.config.js" I receive the following error as shown in the stack trace. It seems like it could be a trivial problem, however I can't seem to identify the root of the issue in order to debug. Full Stack Trace SyntaxError: Unexpected token ) at NativeCompileCache._moduleCompile (.\node_modules\v8-compile-cache\v8-compile-cache.js:226:18) at Module._compile (.\node_modules\v8-compile-cache\v8-compile-cache.js:172:36) at Object.Module._extensions..js (module.js:654:10) at Module.load (module.js:556:32) at tryModuleLoad (module.js:499:12) at Function.Module._load (module.js:491:3) at Module.require (module.js:587:17) at require (.\node_modules\v8-compile-cache\v8-compile-cache.js:159:20) at WEBPACK_OPTIONS (.\node_modules\webpack-cli\bin\convert-argv.js:133:13) at requireConfig (.\node_modules\webpack-cli\bin\convert-argv.js:135:6) at .\node_modules\webpack-cli\bin\convert-argv.js:142:17 at Array.forEach (<anonymous>) at module.exports (.\node_modules\webpack-cli\bin\convert-argv.js:140:15) at yargs.parse (.\node_modules\webpack-cli\bin\cli.js:241:39) at Object.parse (.\node_modules\yargs\yargs.js:552:18) at .\node_modules\webpack-cli\bin\cli.js:219:8 at Object.<anonymous> (.\node_modules\webpack-cli\bin\cli.js:530:3) at Module._compile (module.js:643:30) at Object.Module._extensions..js (module.js:654:10) at Module.load (module.js:556:32) at tryModuleLoad (module.js:499:12) at Function.Module._load (module.js:491:3) at Module.require (module.js:587:17) at require (internal/module.js:11:18) at module.exports.filename (.\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\import-local\index.js:16:66) at .\AppData\Roaming\npm\node_modules\webpack-cli\bin\cli.js:13:6 at Object.<anonymous> (.\AppData\Roaming\npm\node_modules\webpack-cli\bin\cli.js:530:3) at Module._compile (module.js:643:30) at Object.Module._extensions..js (module.js:654:10) at Module.load (module.js:556:32) -
How do I fetch and work with request data being posted through a Web API?
I'm building an endpoint that takes in car details and calculates their insurance payment with the django rest framework. Here's my models.py file from django.db import models import uuid # from calculateInsurance import views # Create your models here. class Car(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) make_of_vehicle = models.CharField(max_length = 50) type_of_risk = models.CharField(max_length = 50) cubic_capacity = models.PositiveIntegerField(blank=True,null=True) registration_number = models.CharField(max_length = 50) chassis = models.CharField(max_length = 50, blank = True, null=True) engine_number = models.CharField(max_length=50, blank = True, null=True) year = models.CharField(max_length = 4, blank=True, null=True) number_of_seats = models.IntegerField() license_issued_year = models.CharField(max_length=4) insurance_type = models.CharField(max_length=50) insurance_payment_due = models.IntegerField(editable=False, default=333, null=True) def __str__(self): return "{} {}".format(self.type_of_risk, self.insurance_type) What I'm trying to do is set the default attribute of insurance_payment_due to a particular method based on the insurance_type and type_of_risk entered. The problem here is how to determine the values entered into those fields when they're being posted. I've seen a couple of posts that suggested that I use request.data but then I'm not entirely sure how I should use it. Here's my views.py file from django.shortcuts import render from calculateInsurance.models import Car from rest_framework import generics from rest_framework.response import Response from rest_framework.reverse import reverse from calculateInsurance.serializers import CarSerializer # Create … -
How to host a website in godaddy and install Django server
How to host my website in godaddy and install Django server which Im using for sending a mail upon a visitor inquired about products. I want to do this with single website plan not with VPS. Whethe they will allow me to install python,Django? -
Browser Sync, npm, and Django Development Server
I have been trying to resolve an error message when I run npm start on a Django project. I used this tutorial by Keith Dechant. After spending a couple of hours duck-duck-going (searching) online :), I decided to ask you for help. Here is the error message I get: [0] npm WARN invalid config loglevel="notice" [2] npm WARN invalid config loglevel="notice" [0] [0] > my_project@1.0.0 css-watch C:\Users\ED\Environments\my_project\my_project [0] > node-sass my_project/static/scss -o my_project/static/css --watch [0] [2] [2] > my_project@1.0.0 browser-sync C:\Users\ED\Environments\my_project\my_project [2] > browser-sync start --files "my_project/static/css/*.css, my_project/static/js/*.js, my_project/**/*.py, my_project/templates/*.html" --proxy 127.0.0.1:8000 --reload-delay=300 --reload-debounce=500 [2] [0] fs.js:994 [0] binding.lstat(pathModule._makeLong(path), statValues); [0] ^ [0] [0] Error: ENOENT: no such file or directory, lstat 'C:\Users\ED\Environments\my_project\my_project\my_project\static\scss' [0] at Error (native) [0] at Object.fs.lstatSync (fs.js:994:11) [0] at Object.module.exports.parseDir (C:\Users\ED\Environments\my_project\my_project\node_modules\sass-graph\sass-graph.js:153:10) [0] at Object.watcher.reset (C:\Users\ED\Environments\my_project\my_project\node_modules\node-sass\lib\watcher.js:17:21) [0] at watch (C:\Users\ED\Environments\my_project\my_project\node_modules\node-sass\bin\node-sass:260:20) [0] at run (C:\Users\ED\Environments\my_project\my_project\node_modules\node-sass\bin\node-sass:319:5) [0] at Object.<anonymous> (C:\Users\ED\Environments\my_project\my_project\node_modules\node-sass\bin\node-sass:405:3) [0] at Module._compile (module.js:570:32) [0] at Object.Module._extensions..js (module.js:579:10) [0] at Module.load (module.js:487:32) [0] npm ERR! code ELIFECYCLE [0] npm ERR! errno 1 [0] npm ERR! my_project@1.0.0 css-watch: `node-sass my_project/static/scss -o my_project/static/css --watch` [0] npm ERR! Exit status 1 [0] npm ERR! [0] npm ERR! Failed at the my_project@1.0.0 css-watch script. [0] npm ERR! This is probably not a problem … -
Django starting id field from 1000
I would like to start my ids on a django model from 1000. I've found this response on Stackoverflow but I am missing something in my implementation because it is not working. This is my code in apps.py from django.apps import AppConfig from django.db.models.signals import post_migrate from django.db import IntegrityError from invoice.models import Invoice def my_callback(sender, **kwargs): if sender.name =="invoice": try: Invoice.objects.create(id=999) Invoice.objects.delete() except IntegrityError: pass class InvoiceConfig(AppConfig): name = 'invoice' def ready(self): post_migrate.connect(my_callback, sender=self) I've then ensure migrate takes place but the model continues to increment from low numbers. What am I missing? -
django.conf import settings vs from project.settings import VAR
I was reading this article here about django settings I understand "that django.conf.settings isn’t a module – it’s an object." That's why I can't import variables. I only need the statement CURRENCIES in my settings. Is the right approach to do from django.conf import settings and then var = settings.CURRENCIES or can I do from [projectname].settings import CURRENCIES Both is working for me. But I wonder if there is a recommended approach. -
WSGI module on Apache - CentOS - Django
first, a lot of thanks to all people in StackOverFlow that i follow post to solve my deployment problems. I will deploy my django website with this global config: Django = 2.0.6 CentOS = 7.5.1804 Apache = 2.4.6 Python = 3.6 I solved with this posts the SELinux security problem : https://www.security-helpzone.com/2017/02/20/centos-7-apache-2-4-resoudre-acces-403-forbidden/ And i follow this post https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-centos-7 with the official doc https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/modwsgi/ The Django project work perfectly with migrate and runserver. I make the rights permissions on the Django project and on the virtualenv folder. But i am blocked (i think) on a problem of mod_wsgi loading with two methods that i see on help forums. Method 1 install mod_wsgi with yum and i have this error on the error_log of apache : [Wed Jun 13 14:31:08.539328 2018] [mpm_prefork:notice] [pid 246229] AH00170: caught SIGWINCH, shutting down gracefully [Wed Jun 13 14:32:08.599932 2018] [core:error] [pid 246234] [client 94.183.176.161:59537] Script timed out before returning headers: wsgi.py [Wed Jun 13 14:47:57.245954 2018] [core:notice] [pid 250772] SELinux policy enabled; httpd running as context system_u:system_r:httpd_t:s0 [Wed Jun 13 14:47:57.246851 2018] [suexec:notice] [pid 250772] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Wed Jun 13 14:47:57.256015 2018] [auth_digest:notice] [pid 250772] AH01757: generating secret for digest authentication ... … -
In Django ModelAdmin, how to allow editing of ForeignKey objects but not reassignment?
I work with structure which can be simplified like this: # models.py class Order(models.Model): payment = models.ForeignKey('Payment', null=True, on_delete=models.PROTECT) # other fields class Payment(models.Model): # fields # admin.py @admin.register(Payment) class PaymentAdmin(admin.ModelAdmin): model = Payment fields = (...) readonly_fields = (...) def get_model_perms(self, request): return {} def has_delete_permission(self, request, obj=None): return False def has_add_permission(self, request): return False @admin.register(Order) class OrderAdmin(admin.ModelAdmin): model = Order fields = ('payment', ...) now, what I want to do is to allow the Payment object to be edited from popup in OrderAdmin by clicking the pencil icon. However, I don't want to allow the admin to reassign it (to change linked payment from PaymentObject(1) to PaymentObject(2) or to null for example). Because I want to be able to edit the payment, I can't mark the payment field as read only. I can't change the ForeignKey relation, because that would require huge refactor. I would prefer a solution that only deals with forms, but even a hacky one is better than nothing I suppose. -
Django - list of choice in a ModelForm
I want to customize a modelForm with a list of choices from 0 to 10. I tried to add a widget, but can't figure out how to make it work : class AbonnementsForm(ModelForm): class Meta: model = Abonnements fields = [ "nombre_d_exemplaire" ] widgets = {'"nombre_d_exemplaire" : forms.ChoiceField(widget=forms.RadioSelect, choices=range(10)) } Gives me an error : 'ChoiceField' object has no attribute 'is_hidden' -
Collect data from a class based form UpdateView django for use in views.py
I have a form based on my model "configuration" : models.py class configuration(models.Model): Num_ordre = models.CharField(max_length=15) Composant = models.CharField(max_length=15) Designation = models.CharField(max_length=15) Qte_servie = models.IntegerField() Qte_a_servir = models.IntegerField() Lot = models.CharField(max_length=15) Categorie = models.CharField(max_length=15) Famille = models.CharField(max_length=15) From this model I create a form with the UpdateView function : views.py class ComposantUpdate(UpdateView): model = configuration fields = '__all__' template_name = 'accueil/exploitation/update_composant.html' success_url = reverse_lazy('cahier', args=('OFTSP1611000853',))` My problem is that the success_url gets an argument I have entered manually : OFTSP1611000853 which corresponds to configuration.Num_ordre for pk=1. Instead of 'OFTSP1611000853' I want to put the data written by the user in the corresponding field in the form. How can I collect this value ? -
what type of databse relationship should i use?
from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ('headline',) I found this one to many relationship examples in the Django docs, how would I go about doing another class called Magazine. In the class magazine, it would contain many articles written by many reporters. Would I still use a many to one- relationship, or would I need a one-to-one relationship? Thanks, in a advance for any help -
Using django-bootstrap4 + django_icons + my custom css files
I am new to Django and how a combinations packages work when loaded into a django template. I want to use django-bootstrap4 along with django_icons and my custom css files for a project, but I do not understand how they all fit together. Such as, what goes into the base.html and .html files that extend the base.html. Also, I want to style the django templates with my own custom external css file. -
Django URL Parameters get deleted
Hey guys I'm having a problem passing URL parameters in my Django code. Let say i have a url like: /search/?q=django and in one of my form I have a href to add another parameter like <a href="?price=all"> ... </a> But when I actually click the href link I end up with: search/?price=all and the django spits out a "ValueError: Cannot use None as a query value" any idea of why this is happening?? -
Django:get_queryset() is not popping up filter() method
I wrote a custom model manager in my Django project and below the code is from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'DRAFT'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title while executing Post.published.filter(title__startswith='Who') in command shell I am getting below error AttributeError: 'PublishedManager' object has no attribute 'filter'. -
Django Send_Mail Authentication Failure
I am using my mail server to send mail using Django. When I try to use the send_mail function, I am met with an authentication error. I know that it is not the password, because I can use it to login to my mail account. How My Mail Server is Setup I am running Ubuntu 16.0.4 with Nginx and Gunicorn for my Django application. I have installed Roundcube, postfix and dovecot. How Do I add Users to Roundcube? For me, the only way I know how to do this is by just adding a new user from the CLI using adduser <user> and from there, logging into Roundcube so that my new user is added to the Roundcube database, and I have an accessible account on Roundcube. What I Suspect to be The Issue Since I am creating the users for Roundcube directly from the CLI and they are full Unix users, I can only login to Roundcube using their actual username, and not username@domain.tld. I suspect that Django is trying to authenticate with user@domain.tld rather than user and that is what is causing the issue. How Can I Fix This? I am not sure, hence why I am here. … -
Flake8 error `E712 comparison to True should be 'if cond is True:' or 'if cond:'` in django
I try to manage if condition in Django. It's working fine but getting an error when trying to check with flake8 flake8 data/view.py My condition like this: if user.item.purchase.status == True: Here user, item and purchase is model and status is a field of purchase. I'm doing something wrong? Flake8 error E712 comparison to True should be 'if cond is True:' or 'if cond:' Thanks in advance -
Websockets configuration with nginx and SSL [Django]
After adding the SSL certificates successfully, we are getting a timeout error on the browser. See here screenshot of the browser's log: https://drive.google.com/file/d/1S3WiUlALcNfYEKo3SENMmga9ktDUaNgb/view?usp=sharing Has anyone experienced anything similar? Please, let me know if you need more details of the set up. See below our nginx configuration listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/casista.com-0001/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/casista.com-0001/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot upstream chatserver { server ec2-13-58-129-240.us-east-2.compute.amazonaws.com:8765; } client_max_body_size 4G; access_log /var/log/nginx/casista-access.log; error_log /var/log/nginx/casista-error.log; location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://unix:/home/ubuntu/mywasi-root/mywasi/mywasi.sock; break; } # include proxy_params; location /ws { # proxy_pass http://ec2-13-58-129-240.us-east-2.compute.amazonaws.com:8765; proxy_pass http://chatserver; # proxy_pass http://localhost:8765; proxy_connect_timeout 7d; proxy_read_timeout 7d; proxy_send_timeout 7d; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } auth_basic "Restricted content"; auth_basic_user_file /etc/nginx/.htpasswd; } location /static/ { alias /home/ubuntu/mywasi-root/mywasi/staticfiles/; autoindex off; } location /media/ { alias /home/ubuntu/mywasi-root/mywasi/media/; autoindex off; } @polrodoreda -
How to display model manager filtered data in django templates
I am trying to display the data filtered by the queryset from my Project model.py in my EmployeDetailView view, using a template, and a model manager. I have this models.py , this view call "EmployeDetailView" , and a templates call "employe_detail.html", and i don't know how to proceed :/ Models : class CondiSalaireManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(matriculeemp__matriculeemp=1) class Salaire(models.Model): date = models.DateField(db_column='Date') charge_patronale_mensuel = models.FloatField(db_column='Charge_Patronale_Mensuel', blank=True, null=True) charge_salariale_mensuel= models.FloatField(db_column='Charge_Salariale_Mensuel', blank=True, null=True) autre_charge_mensuel_fixe = models.FloatField(db_column='Autre_Charge_Mensuel_Fixe', blank=True, null=True) salaire_brut_mensuel = models.FloatField(db_column='Salaire_Brut_Mensuel', blank=True, null=True) matriculeemp = models.ForeignKey(Employe, models.DO_NOTHING, db_column='MatriculeEmp', blank=True, null=True, related_name='photos') salaire_net_mensuel = models.FloatField(db_column='Salaire_Net_Mensuel', blank=True, null=True) charge_variable_mensuel = models.FloatField(db_column='Charge_Variable_Mensuel', blank=True, null=True) condi_objects = CondiSalaireManager() class Meta: db_table = 'salaire' ordering = ["date"] get_latest_by = 'date' View : class EmployeDetailView(DetailView): model = Employe context_object_name = 'employe' -
Django: embedding image in template
I need an image to be displayed within my webpage. The image is stored within a variable in views.py. Most solutions such as the one below use HttpResponse to output images but I want the image to be embedded within my html template. from django.http import HttpResponse def my_image(request): image_data = open("/path/to/my/image.png", "rb").read() PS. I am getting the image by using matplotlib to create the image. So I cannot use a static folder. Example code given below (credit:this) import sys from django.http import HttpResponse import matplotlib as mpl mpl.use('Agg') # Required to redirect locally import matplotlib.pyplot as plt import numpy as np from numpy.random import rand try: # Python 2 import cStringIO except ImportError: # Python 3 import io def get_image(request): """ This is an example script from the Matplotlib website, just to show a working sample >>> """ N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses plt.scatter(x, y, s=area, c=colors, alpha=0.5) """ Now the redirect into the cStringIO or BytesIO object >>> """ if cStringIO in sys.modules: f = cStringIO.StringIO() # Python 2 else: f = io.BytesIO() # Python 3 plt.savefig(f, format="png", … -
Password reset link generation
How Django version 1.11 generates a password reset link with uid and token generator for the given user. How it validates the link. After some digging, I found out they save the token in session to check afterwords, but in that case validity of such link is highly unreliable(i think, might be wrong). Please, suggest me some functions which will do the same i.e. generate encrypted email link which will be used to reset email. -
Count the usage of a many to many field in Django for string representation
My Topic model has a ManyToMany Relation to the Post modell. As part of it's string representation I wanted to have its usage count but I'm unsure how to query that. class Topic(models.Model): posts = models.ManyToManyField(Post) name = models.CharField(max_length=100, blank=False) def __str__(self): return self.name so in addition to self.name I'd like to return the count how often that very Topic is used on Posts. -
django-admin startproject results in "ModuleNotFoundError: No module named 'config'"
My setup is: - Mac OS running pyenv installed with homebrew. - python 3.6.5 virtualenv - pip install Django==2.0.6 Here is the command I issued and the output. The only answers I've found when I search for this assume an existing django project, and incorrect configuration. I am unable to get to the point of creating the project. $ django-admin startproject justatestproj Traceback (most recent call last): File "/Users/rsquire/.pyenv/versions/forever7pi/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/Users/rsquire/.pyenv/versions/3.6.5/envs/forever7pi/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/rsquire/.pyenv/versions/3.6.5/envs/forever7pi/lib/python3.6/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/Users/rsquire/.pyenv/versions/3.6.5/envs/forever7pi/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/rsquire/.pyenv/versions/3.6.5/envs/forever7pi/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Users/rsquire/.pyenv/versions/3.6.5/envs/forever7pi/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/rsquire/.pyenv/versions/3.6.5/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked … -
Django: sort by related model with multiple criteria, put nulls last
So this super long query almost works as needed: context['user_artists'] = Artist.objects.filter(users=current_profile) \ .prefetch_related(Prefetch('release_groups', queryset=ReleaseGroup.objects.filter(release_date__isnull=False, release_date__gte=startdate) .order_by('release_date'), to_attr='rgs')) \ .annotate(next_release=Max('release_groups__release_date')).order_by(F('next_release').desc(nulls_last=True)) Basically, this puts all the nulls last, BUT - since I want the SOONEST next release, this doesn't work. It puts first the FARTHEST next release. What I need is this order: Artist X - next release date: 6.12.18 Artist Y - next release date: 6.31.18 Artist Z - next release date: Null -
Django filter exclude with ReverseManager
I'm fairly new to Django so bare with me. I have a model Tenant and a model SocialMediaContextTenant that has a foreign key to the Tenant model. class SocialMediaContextTenant(AbstractSocialMediaContext): tenant = models.ForeignKey('campaigns.Tenant') secret = models.CharField(...) I would like filter all tenants where a connected SocialMediaContextTenant has the secret field set. So far I have this query Tenant.objects .exclude(socialmediacontexttenant__secret='') .values_list('id', flat=True) But the exclude filter does not seem to work, since I still get results with an empty secret field -
How to pass file from django app to flask app?
I have a flask app for another different project. I am trying to use a module from my flask app as a support for my django app. That is, I read an audio file in the django app directory and send it to the flask app using requests.post method. And, the method in flask app does whatever it needs to. This is what I've tried: In django view: try: f = open(os.path.join(settings.AUDIO_FILES_DIR, '2/1-Minute_Audio.mp3'), 'rb') requests.post('http://0.0.0.0:9090/upload', data={'file': f}) except Exception as e: print(e) In flask app: from flask import Flask, request app = Flask(__name__) @app.route("/upload", methods=['POST']) def upload(): try: f = request.files['file'] f.save('save/path', f.filename) return "Success !" except Exception as e: print(e) return "No Success !" if __name__ == "__main__": app.run(host='0.0.0.0', port=9090)