Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
check if field is empty and populate it with another field in django
Recently i built a super tiny inventory system. it generates barcode from the item id. so now now I want to add the functionality of using an already generated code to search for item. So i have the fields like this previously class Inv(models.Model): description = models.CharField() model_number = models.CharField() manufacturer = models.CharField() def __str__(self): return self.id Now class Inv(models.Model): description = models.CharField() model_number = models.CharField() manufacturer = models.CharField() barcode = models.CharField(blank=True) def __str__(self): return self.id what I want to achieve is in a situation where an item doesn't have a barcode image and I want to save the item and add the id into the barcode field how do I do that efficiently? this is the save method I have written def save(self, force_insert=False, force_update=False, *args,**kwargs): # if self.barcode == None: # self.barcode = self.id # self.save() super(Inv, self).save(force_insert, force_update, *args, **kwargs) -
How to push flat data with POST in nested serializer DRF
I have an API that can create testruns, but I need an instrument serial number to create it. I would like to be able to have this POST request : { "serial_number":"4331214L" "operator": "John Doe" } But, right now I have to do : { "instrument": { "serial_number":"4331214L" }, "operator": "John Doe" } current models: class InstrumentModel(models.Model): class Meta: db_table = "instruments" verbose_name = "Instrument" serial_number = models.CharField(max_length=10, unique=True, db_index=True) def __str__(self): return self.serial_number class TestRun(models.Model): class Meta: db_table = "test_runs" verbose_name = "Test run" operator = models.CharField(max_length=70) instrument = models.ForeignKey(InstrumentModel, related_name="instruments", db_column="instrument", on_delete=models.CASCADE) created_at = models.DateTimeField(db_index=True, default=timezone.now) I tried with the depth meta field. That doesn't work. Maybe it's not at the serializer level? class TestRunSerializer(serializers.ModelSerializer): instrument = InstrumentSerializer() class Meta: model = TestRun fields = ('operator', 'instrument') depth = 1 -
Reverse for 'note_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['notes\\/(?P<slug>[-\\w]+)/$']
NoReverseMatch at /notes/ Reverse for 'note_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['notes\/(?P[-\w]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/notes/ Django Version: 2.0.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'note_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['notes\/(?P[-\w]+)/$'] Exception Location: C:\Users\auwwa\Desktop\notes\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632 Python Executable: C:\Users\auwwa\Desktop\notes\Scripts\python.exe Python Version: 3.6.4 Python Path: ['C:\Users\auwwa\Desktop\notes\src\notes', 'C:\Users\auwwa\Desktop\notes\Scripts\python36.zip', 'C:\Users\auwwa\Desktop\notes\DLLs', 'C:\Users\auwwa\Desktop\notes\lib', 'C:\Users\auwwa\Desktop\notes\Scripts', 'C:\Users\auwwa\AppData\Local\Programs\Python\Python36\Lib', 'C:\Users\auwwa\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\auwwa\Desktop\notes', 'C:\Users\auwwa\Desktop\notes\lib\site-packages'] Server time: Wed, 24 Oct 2018 21:18:57 +0000 I have problem Reverse for 'note_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['notes\/(?P[-\w]+)/$'] this is viewes detail : def detail(request, slug): note = Note.objects.get(slug=slug) context = { 'note':note } return render(request, 'note_detail.html', context) and this urls page: from django.conf.urls import url from . import views ////url notes_app//// app_name = "notes_app" urlpatterns = [ url(r'^$', views.all_notes, name='all_notes'), url(r'^(?P<slug>[-\w]+)/$', views.detail , name='note_detail'), url(r'^Add$', views.note_add, name='add_note'), ] -
Forbidden (CSRF token missing or incorrect.) After CSRF token login success
I use below code to first login to my website to get the valid CSRF token, then I would like to use that token to make API call, however, it failed. Please help me.. import requests LOGIN_URL = 'http://localhost:8000/admin/login/' client = requests.session() # Retrieve the CSRF token first client.get(LOGIN_URL) csrftoken = client.cookies['csrftoken'] print('token:'+ csrftoken) login_data = dict(username='xxxx', password='xxxx', csrfmiddlewaretoken=csrftoken) r1 = client.post(LOGIN_URL, data=login_data, headers=dict(Referer=LOGIN_URL)) print(r1.status_code, r1.reason) print('token:'+ csrftoken) API_URL = 'http://localhost:8000/collection/api/job_submit/' payload = {'csrfmiddlewaretoken': csrftoken, 'value1': 'val', 'value2': 'val'} r2 = client.post(API_URL, data=payload, headers={'referer': API_URL, 'X-CSRFToken': csrftoken}) print(r2.status_code, r2.reason) And this is what I get from the server: [24/Oct/2018 21:28:59] "GET /admin/login/ HTTP/1.1" 200 1806 [24/Oct/2018 21:28:59] "POST /admin/login/ HTTP/1.1" 302 0 [24/Oct/2018 21:28:59] "GET /accounts/profile/ HTTP/1.1" 404 91 2018-10-24 21:28:59,914 [WARNING] django.security.csrf: Forbidden (CSRF token missing or incorrect.): /collection/api/job_submit/ [24/Oct/2018 21:28:59] "POST /collection/api/job_submit/ HTTP/1.1" 403 1019 So, how can I pass the token correctly? -
Unable to use python variables in html | Django
I am using django to create a web app. I have run into a problem when trying to use variables from python in html. The variable does not show up. The app has a lot of messy code so I have recreated the problem including only relevant files. views.py: from django.shortcuts import render # Create your views here. def home(request): return render(request, 'main/index.html') def hello(request): if request.method == 'POST': fname = request.POST.get('fname', None) else: fname = "there" return render(request, 'main/hello.html') index.html: {% extends "base.html" %} {% block content %} <form action="hello" method="POST"> {% csrf_token %} <input name="fname" placeholder="First Name"> <input type="submit" value="Submit"> </form> {% endblock content %} hello.html {% extends "base.html" %} {% block content %} <p>Hello {{fname}}</p> {% endblock content %} base.html: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello</title> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="{% static "css/style.css" %}"> </head> <body> {% block content %}{% endblock content %} </body> </html> Here is what the "hello" page looks like(only part of the screen): I want it to be able to output the users input. -
How to track actions made by user, even those made with AJAX?
In my website I am tracking any actions made by users, pages viewed one by one. In some views, I do some ajax requests like: def books_list(request): books_list = Book.objects.filter(published=True).order_by('-timestamp') if request.method == 'POST' and request.is_ajax(): id_book = request.POST.get('id_book') try: book = books_list.get(id=id_book) book.delete() except Book.DoesNotExist: return JsonResponse({'error':True,'msg':'Book not found'}) render(request,'book/books-list.html',context={'books_list':books_list}) Here'is a quick view of how it looks like: *# analytics * - / # the home page - /books/ # visits list of books - /books/ # He deletes a book - /books/ # back to list of books As you can see, When user deletes a book, tracking keeps the same URL /books/obviously, How can I have it like: *# analytics * - / # the home page - /books/ # visits list of books - /books/delete # He deletes a book - /books/ # back to list of books Do I need to create new view/url for the simple delete action? -
custom Django Admin form -- adding a button that does API calls
I want to add a custom button that calls for an API endpoint when i click it and return to previous page. I have my custom form as {% extends 'admin/change_list.html' %} {% block object-tools %} <div> <form method="POST"> {% csrf_token %} <button type="submit">Update Sumamry</button> </form> </div> <br /> {{ block.super }} {% endblock %} I probably need to add action to form, but I don't know what to do here. in my admin.py, I have class MyFuncAdmin(admin.ModelAdmin): def update_summary(self): # do the API call here return HttpResponseRedirect("../") several question: Is my approach correct? What do I need to do to call my API, say the endpoint is localhost:8000/some/endpoint or reverse('myendpoint') -
How to json response list of querysets in Django?
I'm trying to make a json response from a list of querysets The list is like this print("List of querysets", rq) List of querysets [ <QuerySet [<Request: Request object (1)>]>, <QuerySet [<Request: Request object (2)>]>, <QuerySet [<Request: Request object (3)>]> ] I'm doing it like that but I have this error json_rq = serializers.serialize('json', rq) return HttpResponse(json_rq, content_type='application/json') AttributeError: 'QuerySet' object has no attribute '_meta' And also this return JsonResponse(rq, safe=False) TypeError: Object of type 'QuerySet' is not JSON serializable Any ideas? -
Django whole DB export to XLS
I have found several tools, such as django-import-export, that allows exporting a model's objects in an XLS table. Here is the sample code found in the django-import-export docs: from django.http import HttpResponse from .resources import PersonResource def export(request): person_resource = PersonResource() dataset = person_resource.export() response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="persons.xls"' return response How would I go about exporting every models in separate tabs in the same XLS file? Can I somehow insert data in the "dataset" variable? Thanks a lot! -
How to test Django CreateView and form_valid
This maybe very basic but I still fail to understand how to test a Django CreateView which has a form_valid(self, form) method ? Here's my code: class NewPatientFormView(LoginRequiredMixin, CreateView): model = Patient fields = ['name', 'surname', 'phone', 'email', 'PESEL', 'age', 'patient_agreement'] def form_valid(self, form): self.object = form.save(commit=False) self.object.created_by_user = self.request.user self.object.save() return super().form_valid(form)` I'm using pytest and I simply fail to understand how to test this one. I would be really grateful for a short example how this could be tested ... Thanks! -
Heroku Bad Request Server Error 500 for Django Web app
I'm deploying a Django web app in production on Heroku. I receive a Server Error (500) after checking with heroku logs --tail. I'm not sure how to get rid of the user warning which may be causing the issue. Note, I'm running the app from a prod.py file with my wsgi.py set as: wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings.prod") # mysite.settings.prod when in prod application = get_wsgi_application() Moreover, in the Heroku CLI I've set: SET DJANGO_SETTINGS_MODULE=mysite.settings.prod Any advice is much appreciated. requirements.txt akismet==1.0.1 certifi==2018.10.15 chardet==3.0.4 dj-database-url==0.5.0 Django==2.1.2 django-heroku==0.3.1 gunicorn==19.9.0 idna==2.7 pytz==2018.5 requests==2.20.0 urllib3==1.24 whitenoise==4.1 psycopg2-binary==2.7.5 Log File from Heroku CLI 2018-10-24T19:19:32.262690+00:00 app[web.1]: [2018-10-24 19:19:32 +0000] [11] [INFO] Worker exiting (pid: 11) 2018-10-24T19:19:32.262706+00:00 app[web.1]: [2018-10-24 19:19:32 +0000] [10] [INFO] Worker exiting (pid: 10) 2018-10-24T19:19:32.262708+00:00 app[web.1]: [2018-10-24 19:19:32 +0000] [4] [INFO] Handling signal: term 2018-10-24T19:19:32.357695+00:00 app[web.1]: [2018-10-24 19:19:32 +0000] [4] [INFO] Shutting down: Master 2018-10-24T19:19:32.441038+00:00 heroku[web.1]: Process exited with status 0 2018-10-24T19:19:38.848024+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi` 2018-10-24T19:19:41.369271+00:00 app[web.1]: [2018-10-24 19:19:41 +0000] [4] [INFO] Starting gunicorn 19.9.0 2018-10-24T19:19:41.369754+00:00 app[web.1]: [2018-10-24 19:19:41 +0000] [4] [INFO] Listening at: http://0.0.0.0:58681 (4) 2018-10-24T19:19:41.369856+00:00 app[web.1]: [2018-10-24 19:19:41 +0000] [4] [INFO] Using worker: sync 2018-10-24T19:19:41.373709+00:00 app[web.1]: [2018-10-24 19:19:41 +0000] [10] [INFO] Booting worker … -
Forms not clickable inside div in HTML
I am writing an app in Django and it works perfectly fine when not including divs but when including divs, I cannot click on any forms or texts after the post request (weirdly, it works fine before the post request). <!DOCTYPE html> <html lang="en"> <head> <title>Some title</title> <link rel="stylesheet" href="https://cdn.pydata.org/bokeh/release/bokeh-0.13.0.min.css" type="text/css" /> </head> <div style="width:300px; float:left;"> <body> {% block content %} <form method="post" action=""> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Calculate"/> </form> {% endblock %} </body> </div> I am very new to HTML but I read that it is related to CSS somehow but I want to avoid fiddling with that when using Django. -
Django object is not iterable. How to get most viewed object
Hi I am newbie and i am getting error "'Zagrania' object is not iterable". I want to get most viewed object and display it differently (wyswietlenia-views of object) views.py def zagrania(request): zagrania = Zagrania.objects.all().order_by('-data') najepszezagranie = Zagrania.objects.all().order_by('-wyswietlenia').first() return render(request, 'zagrania/zagrania.html', { 'zagrania':zagrania, 'najepszezagranie':najepszezagranie}) models.py class Zagrania(models.Model): tytul = models.CharField(max_length=70) data = models.DateTimeField(auto_now_add=True) autor = models.ForeignKey(User,on_delete=models.CASCADE,default=None) opis = models.TextField(max_length=276, default='') wyswietlenia = models.PositiveIntegerField(default=0) filmik = models.FileField(upload_to="static/filmiki") #votes= models.IntegerField(default=0) template {% for zagranie in najepszezagranie %} <a href="{% url 'zagrania_detail' zagranie.id%}"> <video> <source src="{{ zagranie.filmik.url }}" type="video/mp4"></source> </video> </a> <a href="{% url 'zagrania_detail' zagranie.id%}">{{ zagranie.tytul }}</a> {% endfor %} -
django_helpdesk - namespaces - 'en-us' is not a registered namespace
I am working with django and integrating the third party app - django_helpdesk. I had this working previously and since my updated to django 1.11 and helpdesk 0.2.10 im getting errors. when i run the management command get_email - I recieve an error "django.urls.exceptions.NoReverseMatch: 'en-us' is not a registered namespace" Traceback (most recent call last): File "manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/home/website/public_html/prodenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/website/public_html/prodenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/website/public_html/prodenv/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/website/public_html/prodenv/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/website/public_html/prodenv/lib/python2.7/site-packages/helpdesk/management/commands/get_email.py", line 77, in handle process_email(quiet=quiet) File "/home/website/public_html/prodenv/lib/python2.7/site-packages/helpdesk/management/commands/get_email.py", line 110, in process_email process_queue(q, logger=logger) File "/home/website/public_html/prodenv/lib/python2.7/site-packages/helpdesk/management/commands/get_email.py", line 240, in process_queue ticket = ticket_from_message(message=full_message, queue=q, logger=logger) File "/home/website/public_html/prodenv/lib/python2.7/site-packages/helpdesk/management/commands/get_email.py", line 503, in ticket_from_message context = safe_template_context(t) File "/home/website/public_html/prodenv/lib/python2.7/site-packages/helpdesk/lib.py", line 260, in safe_template_context 'ticket': ticket_template_context(ticket), File "/home/website/public_html/prodenv/lib/python2.7/site-packages/helpdesk/lib.py", line 220, in ticket_template_context attr = getattr(ticket, field, None) File "/home/website/public_html/prodenv/lib/python2.7/site-packages/helpdesk/models.py", line 547, in _get_ticket_url reverse('helpdesk:public_view'), File "/home/website/public_html/prodenv/lib/python2.7/site-packages/django/urls/base.py", line 87, in reverse raise NoReverseMatch("%s is not a registered namespace" % key) django.urls.exceptions.NoReverseMatch: 'en-us' is not a registered namespace *en-us is whatever I put in my language code within settings.py* I came across this article and tried switching the reverse() call, referenced … -
cannot import django running apache2 server
I know that many have posted similar question however I tried most solution without success. I'm trying to host a webpage with apache2 and django. In the error log I found ImportError: No module named 'django' when accessing the wsgi.pyfile, where I also added import sys, sys.version to confirm which python version is used and from the error log I can see that I'm running following python version 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609]. Now when I run python3.5 I see that I uses the same python version and here I can run import django without any error! Any thoughts what I might have messed up? -
Javascript file can't find the json file in the same static folder in Django
I have a js file in the static folder that help render the front end of the Django project. The static folder is correctly linked. But the js can't find a json file that is in the same static folder. I only have 1 app in my project. -
Hosting 2 Django Applications on Production VM
I have 2 Django web applications and I wanted to host them on a single virtual machine. Currently they are being hosted on 2 physical servers. I am using a windows 2012 R2 Server for hosting them. I am using task schedulers for running my application and it will automatic start on system restart. If I put both the web apps on a single VM running on different ports then if 1 applications crashes the other will suffer because the System Administrator might restarts the VM. Also, I was thinking of a container based solution(docker) but I am not sure how it will work on a windows server. Would it be better to allocate 2 VM's for 2 Apps or is there any better solution. -
gunicorn 19.0: SERVER_NAME in request header is 127.0.0.1
I have upgraded gunicorn to 19.0, now SERVER_NAME is 127.0.0.1 before it was the correct host name of server 'test_server.com'. my settings: Gunicorn: bind = "127.0.0.1:8000" Nginx reverse proxy: server_name test_server.com; upstream test_server { server http://127.0.0.1:8000; } ... proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $server_name; proxy_redirect off; proxy_pass http://test_server; My Django app showing request.META['SERVER_NAME']=='127.0.0.1' , I am using SERVER_NAME header at lot of places and don't want to replace this with HTTP_HOST to get host. -
How to resolve infinite loop caused by onLoadSubmit() of HTML form using Django for backend
I have a form that I want to submit dynamically once the page is loaded. one of the form field is preselected post_city loaded through an URL and preselected among many options. The Django template is as follow: <body onload="onLoadSubmit()"> <form id="headerform" method="GET" action="{% url 'search' %}" data-action="" name="headerform" > <ul id="menu"> <!-- city options --> <span> <li class=""> <select id="post_city" form="headerform" class="" name="h_qc" onchange ="this.submit()"> <option value="{{post_city}}"> {{post_city}} </option> {% for city in all_p_cities %} {% if city.city_name != post_city %} <option value="{{city.city_name}}"> {{city.city_name}} </option> {% endif %} {% endfor %} </select> </li> </span> <!-- category options --> <span> <li > <select id="catAbb" name="h_qcc"> <option value="{{category_name}}"> {{category_name}} </option> </option> {% for category in all_p_categories %} {% if category.category_name != category_name %} <option value="{{category.category_name}}"> {{category.category_name}} </option> {% endif %} {% endfor %} </select> </li> </span> </ul> </form> <script type="text/javascript"> function onLoadSubmit() { document.headerform.submit(); } </script> </body> This is working well except that it gets an infinite loop. That is once the page is loaded, it keeps reloading for infinite that I could not even scroll down the page. Note: I could simply add submit button. However, I want the form is submitted automatically once the page is loaded based on … -
Sync Bitbucket and Webfaction Django
I use Pycharm and push from local machine to Bitbucket. How do I automatically reflect changes on a Webfaction server webapps/myapp? -
setting the django project with Celery
I am trying to set up celery with Django on my development server, running on ubuntu. Following are changes i made. init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] celery.py from __future__ import absolute_import import os from celery import task os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'samplecelery.settings') app = Celery('samplecelery') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py from __future__ import absolute_import from celery import shared_task @shared_task def add(x, y): return x + y @shared_task def mul(x, y): return x * y when i run the command to check the worker for samplecelery celery -A sampleceleryworker -l info app=Celery(samplecelery) It tells me the app is not installed. Any thoughts on what might have gone wrong in this setup?can anyone please help me..... ModuleNotFoundError: No module named 'Celery' -
Processing audio in Django project with Celery
So I have a Django app that uses Celery and pydub to slice audio file in the background. Everything was fine but I'd like to deploy the app to heroku and I have to use AWS S3 to store files. I was struggling with not serializable data so I could pass it to celery task, and I figured out to pass raw bytes data to celery task, and make an BytesIO object from it inside the celery task, and then (pydub) audio object from that BytesIO could be made. I was able to do it in python console, but doing it on Django app shows some utf-8 encodding errors. I tried following this question: Celery worker's log contains question marks (???) instead of correct unicode characters and set the variable LANG in settings.py but it didn't help. I also tried changing the <meta charset> encoding in my base template to utf-16, and that didn't work either. (btw. reversed it back to utf-8 and my my app doesn't want to render even home page now:D) So my questions are: 1) Is there any way to process that audio without having to download it once again directly in my celery task module? … -
Django upload image file through inline formset in testing
temp_file = tempfile.NamedTemporaryFile(dir=os.getcwd(), suffix='.jpeg') data = { 'profile-TOTAL_FORMS': '1', 'profile-INITIAL_FORMS': '1', 'profile-MIN_NUM_FORMS': '1', 'profile-MAX_NUM_FORMS': '1', 'profile-id': self.user.id, 'profile-profile_picture': test_image.name, 'profile-first_name': self.user.first_name, 'profile-last_name': self.user.last_name, } resp = self.c.post(reverse('home:user-profile', kwargs={'pk': self.user.id}), data) i am having trouble with the image uploading through inline formset. The image is not uploading . I think i have to pass the image file through MultiValueDict format i dont know how it can be implemented. plz help me. -
Slug not well configurated in django template
I am trying to use slug to redirect the user to a specific object inside my model, but I am getting the following error: NoReverseMatch at /profile/list Reverse for 'last_config' with no arguments not found. 1 pattern(s) tried: ['profile/history/(?P<id>[^/]+)$'] My urls.py file is doing this inside urlpatterns: path('profile/history/<slug:id>', views.LastConfigView.as_view(), name='last_config'), path('profile/list', views.ListOperationsView.as_view(), name='list_operations'), My template the file (profile/list) is as follows: {% for item in sell_info %} <a href="{% url 'client:last_config' item.id %}">{{ item.date }}</a> {% endfor %} -
getting an unicodecodeerror when performing joblib.load
Getting an Unicodedecodeerror when trying to perform a the joblib dump was done with python 3.6 but joblib.load with python3.5 . Is this expected, since in joblib documentation they say that this might occur if the pickle was done in python2 but loaded in python3. Since the infra of the server is already in python3.5 i am trying to load this into the server Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.5/dist-packages/flask/_compat.py", line 35, in reraise raise value File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/opt/program/predictor.py", line 75, in transformation predictions = ScoringService.predict(data) File "/opt/program/predictor.py", line 41, in predict clf = cls.get_model() File "/opt/program/predictor.py", line 31, in get_model cls.model = joblib.load(inp) File "/usr/local/lib/python3.5/dist- packages/sklearn/externals/joblib/numpy_pickle.py", line 587, in load with _read_fileobject(fobj, filename, mmap_mode) as fobj: File "/usr/lib/python3.5/contextlib.py", line 59, in __enter__ return next(self.gen) File "/usr/local/lib/python3.5/dist packages/sklearn/externals/joblib/numpy_pickle_utils.py", line 144, in _ read_fileobject compressor = _detect_compressor(fileobj) File "/usr/local/lib/python3.5/dist- packages/sklearn/externals/joblib/numpy_pickle_utils.py", line 80, in _detect_compressor first_bytes = fileobj.read(max_prefix_len) File "/usr/lib/python3.5/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0]