Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
give context to page without render
I am trying to make a help section for my team. I have a form that the person that needs help will fill out, then that data will go to a page only my team my can view to see which one of us will tackle the problem. But, I am having trouble rendering the context of the form to the help page my team can view. right now I am using render(), but when the user clicks submit he/she gets redirected to the page only my team should be able to see. and the data doesn't stay on the page when it is reloaded. here is the views.py def help_form(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = HelpForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required name = form.cleaned_data['your_name'] room_number = form.cleaned_data['room_number'] email = form.cleaned_data['email'] when = form.cleaned_data['when'] subject = form.cleaned_data['subject'] description = form.cleaned_data['description'] context = { 'name': name, 'room_number': room_number, 'email': email, 'when': when, 'subject': subject, 'description': description, } # redirect to a new URL: … -
Using $not $in $regex in PyMongo
I want to do a PyMongo equivalent to vendor NOT IN ('Amazon', 'eBay', 'AliBaba'). I am able to get it to work in MongoDB by doing: 'vendor': {'$not': {'$in': [/^Amazon/, /^eBay/, /^AliBaba/]}} This works. In PyMongo no matter what I try, I am getting no result. It is not throwing any errors but not returning any results either. Here is what I have tried: 1) import re vendor = {'$not': {'$in': [re.compile('^Amazon'), re.compile('^eBay'), re.compile('^AliBaba')]}} 2) import re vendor = {'$not': {'$in': [re.compile('.*Amazon.*'), re.compile('.*eBay.*'), re.compile('.*AliBaba.*')]}} What am I missing? Why can't I get not in work with PyMongo? -
How to fix the " unexpected token ']' " error in python3,django2?
I'm trying to add the module to urls.py. Here's the code: """ Definition of urls for learning_log. """ from datetime import datetime from django.urls import path from django.contrib import admin from django.contrib.auth.views import LoginView, LogoutView from app import forms, views #added from django.conf.urls import include, url import learning_logs.views from django.urls import path,re_path app_name='learning_logs' urlpatterns =[ #added path('', include('learning_logs/urls',namespace='learning_logs'), path('contact/', views.contact, name='contact'), path('about/', views.about, name='about'), path('login/', LoginView.as_view ( template_name='app/login.html', authentication_form=forms.BootstrapAuthenticationForm, extra_context= { 'title': 'Log in', 'year' : datetime.now().year, } ), name='login'), path('logout/', LogoutView.as_view(next_page='/'), name='logout'), path('admin/', admin.site.urls)] The code seems alright,but Visual Studio keeps reporting error: unexpected token ']' It says the last ']' has some problem.But it is part of the grammar. How to solve this problem? -
Why does request.FILES["file"].open() is None, though request.FILES.["file"].name works well?
I'm trying to get image file using ajax into Django views.py. I can print the file name and size of it. But when I open the file, it become None..! The reason I'm trying to open image is to use it for vision analysis. Currently I'm working on Django 1.11, python 3.6.7. Here are some codes. views.py def receipt_ocr(request): if request.method == 'POST': print(type(request.FILES["file"])) #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'> print(request.FILES["file"]) #bank.png print(request.FILES["file"].size) #119227 print(request.FILES["file"].name) #bank.png print(request.FILES["file"].content_type) #image/png print(type(request.FILES["file"].open())) #<class 'NoneType'> print(request.FILES["file"].open()) #None print(type(request.FILES["file"].read())) #<class 'bytes'> imageFile = request.FILES["file"] receipt_image = imageFile.read() print(type(receipt_image)) #<class 'bytes'> print(receipt_image) #b'' ajax part in html $.ajax({ url: "{% url 'ocr:receipt_ocr' %}", enctype: 'multipart/form-data', type: 'POST', cache: false, processData: false, contentType: false, data: postData, complete: function(req){ alert('good'); }, error: function(req, err){ alert('message:' + err); } }); I expected the receipt_image in views.py is binary of the image file. But It's empty. Because request.FILES["file"] is None. I don't know why it's None. Thanks your for reading my question. Hope you have a good day👍 -
How can I change the design of the login screen supported by Django?
I'm making a website with Django The login part uses the functions supported by Django. The design doesn't look very good So I want to improve the login screen How can I fix it? I don't know how I don't know which code in which file should be modified If you know how to fix let me knwo please Thank you site : http://terecal-hyun.co.kr/accounts/login/?next=/ github: https://github.com/hyunsokstar/django_inflearn2 -
Django gallery for loop
I want to have a carousel at the top of each of my product pages. I want it to iterate over every image in a directory I specify. Something like this <div id="carouselIndicators" class="carousel slide carousel-fade z-depth-1-half my-4" data-ride="carousel"> <ol class="carousel-indicators"> {% for image in directory %} <li data-target="#carouselIndicators" data-slide-to="0" class="active"></li> {% endfor %} </ol> <div class="carousel-inner" role="listbox"> {% for image in directory %} <div class="carousel-item active"> <img class="d-block img-fluid" src="/media/54521383_989180831273370_3472797838423883776_n.jpg"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> What I want to learn: How to iterate over images in a gallery with a for loop. Is there a better model field for uploading multiple images? eg. galleries Is there a way I can view said images in the Django admin panel? Rather than just the file name. -
How to prevent a Django view that calls an external api from being flooded when it is called by a GET request?
I am writing a Django application with a view that is passed GET parameters. This view contacts an external API to get information, and passes the consolidated information to a template. The external API call is costly and limited. I am concerned that in a production environment, an attacker could write a script to repeatedly load the page with different parameters, (as I'm caching requests, so repeated calls with same parameters are fine), to exhaust my ability to use the external API. I am trying to ensure that only humans can load my view (or specifically, reach the point of the external API call), or, at least, that a robot can't load it hundreds of times. The most elegant solution would be some code in the view before the API call that could validate the user somehow. If the user failed the validation, they could be referred to another view or to a different template with a failure message. I am trying to do this as elegantly as possible and not be sloppy, however, so I'm looking for advice on best practice. Initially, I intuitively wanted to use reCAPTCHA, however, it seems that this is generally used for forms. Adding … -
Docker-compose running local but not remote
I have the following: Dockerfile # Pull base image FROM python:3.7.3-slim # Set environement variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set working directory WORKDIR /code/ # Update system RUN apt update && apt-get -y update RUN apt -y install mysql-client RUN apt -y install python-dev RUN apt -y install gcc RUN apt -y install default-libmysqlclient-dev # Install dependencies RUN pip install pipenv COPY Pipfile Pipfile.lock /code/ RUN pipenv install --system # Copy project COPY . /code/ # Port to expose EXPOSE 8000 # Command to run the webserver CMD ["gunicorn", "gotrakk.wsgi:application", "--bind", "0.0.0.0:8000"] docker-compose.prod.yml version: '3.7' services: web: build: . image: 734309331381.dkr.ecr.us-west-2.amazonaws.com/keeptrakk:latest command: gunicorn gotrakk.wsgi:application --bind 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/code env_file: - environment.txt expose: - "8000" nginx: build: ./nginx image: 734309331381.dkr.ecr.us-west-2.amazonaws.com/nginx:latest ports: - 80:80 - 443:443 depends_on: - web This runs fine when I run local with $(aws ecr get-login --no-include-email --region us-west-2) docker-compose -f docker-compose.prod.yml build docker-compose -f docker-compose.prod.yml push docker-compose -f docker-compose.prod.yml up If I log on to my amazon machine and run the container with eval $(docker-machine env keeptrakk) docker-compose -f docker-compose.prod.yml pull docker-compose -f docker-compose.prod.yml up I get the following ModuleNotFoundError Recreating gotrakk_web_1 ... done Recreating gotrakk_nginx_1 ... done Attaching to … -
Is django python a good/reliable framework for a high performance website?
I intend to build a user interactive website where users can interact with other users via forums, chat, and have algorithms that recommened things to users based on their profile and i'm wondering whether django is powerful enough to deal with high demands? Will django be ideal for server demands that are beyond typical? -
TypeError at /accounts/login/ __init__() takes 1 positional argument but 2 were given
I am using the latest version of django and python 3, When I log in I get the below error message. TypeError at /accounts/login/ init() takes 1 positional argument but 2 were given -
How do I represent items of a L-matrix to store comparison of every item in a collection to every other item?
I am building a Prioritization Matrix/Criteria Matrix[1] within an application and would like to represent Criteria as a Django Model. Now according to the requirements, I need to able able to assign a relative value for each Criteria as compared to every other Criteria in the application. What would be the best way for me to express this relationship ? Essentially, I need to be able to say something like: criteria_1 = Criteria(label='Usefulness', ...) criteria_2 = Criteria(label='Cost', ...) ... ... ... something ... ... ... get_relative_importance(criteria_1, criteria_2) == criteria_2 get_relative_importance(criteria_2, criteria_1) == criteria_2 [1] You can think of it as an L-Matrix like the first image on this page -
How to Fix File Download From Django App Failure
In my django application, the program creates a document and saves it to the file path defined in settings.py MEDIA_URL. If a file exists, the user should able to click on a link in the template and the file should download. When I do this, I get a .docx download, but it reads "Failed - No File". When I look in the folder defined by the file path in settings.py, I can see that the file is there. Any ideas what I may be doing wrong? I feel this should be working since I can see the .docx is being generated correctly. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... MEDIA_ROOT = os.path.join(BASE_DIR, 'web_unit') MEDIA_URL = '/web_unit/' views.py creating the .docx file and saving it def docjawn(request): reference = request.POST.get('Reference_IDs') manifest = Manifests.objects.all().filter(reference__reference=reference) order = Orders.objects.get(reference=reference) doc = DocxTemplate("template.docx") totalCNF = 0 totalFOB = 0 for item in manifest: totalCNF += item.cases * item.CNF totalFOB += item.cases * item.FOB context = { 'ultimate_consignee' : order.ultimate_consignee, 'reference' : order.reference, 'ship_to' : order.ship_to, 'terms' : order.terms, 'date' : "12", 'ship_date' : "7/4/19", 'vessel' : order.vessel, 'POE' : order.POE, 'ETA' : order.ETA, 'booking_no' : order.booking_no, 'manifest' : manifest, 'totalCNF' : totalCNF, 'totalFOB' : totalFOB, } doc.render(context) … -
Django - Create a drop-down list from database data
There is a model field, city, it is filled manually when creating the object. There is a field in the search form, city. In views.py it looks like this: views.py: if 'city' in request.GET: city = request.GET['city'] if city: queryset_list = queryset_list.filter(city__iexact=city) template.html: <div class="col-md-4 mb-3"> <label class="sr-only">City</label> <input type="text" name="city" class="form-control" placeholder="City"> </div> If you enter the name of the city, objects with that name will be selected. It works correctly, but it’s inconvenient. I want the city not to be entered, but selected from the list. This list should be automatically collected from the fields city. How can this be implemented? Thank! -
How to save an array of text in PostgreSQL using Django model.?
I am trying to save an array of text containing category types for a hotel system which looks something like this ['category-1', category-2', category-3, category-4] . I am using category_type = ArrayField(models.CharField(max_length=200),null=True) in my models.py The error i get is malformed array literal: "" LINE 1: ..., '{category-1, category-2}'::varchar(200)[], ''::varcha... ^ DETAIL: Array value must start with "{" or dimension information. The error persist even after processing python list from ['category-1', category-2', category-3, category-4] to {category-1', category-2', category-3, category-4}. I have gone through postgresql documentation and have found very limited help, https://pganalyze.com/docs/log-insights/app-errors/U114 this is something similar posted to what i am facing problem with. Could someone please tell me what am i doing wrong? Any help would be appreciated. -
Django with Vue on sub page in history mode
I have been able to render a Vue app in a Django template when the django url is /. But in this case we want the Django url for the Vue page to be /dashboard. / is just a static Django page. The issue is that the Vue page is showing, but the routes do not work. When I disable history mode, the routes work fine, even on /dashboard/#. So in urls.py I added these lines at the end: re_path( "^dashboard.*$", TemplateView.as_view(template_name="dashboard.html"), name="app", ), in router.ts I have the following configuration: import Vue from 'vue'; import Router from 'vue-router'; import Home from './views/Home.vue'; Vue.use(Router); export default new Router({ mode: 'history', base: `${process.env.BASE_URL}`, routes: [ { path: '/', name: 'home', component: Home, }, { path: '/about', name: 'about', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ './views/About.vue'), }, ], }); I also tried to set base: '${process.env.BASE_URL}/dashboard' which didn't work either. And vue.config.js has the following setup: const BundleTracker = require('webpack-bundle-tracker'); module.exports = { baseUrl: 'http://0.0.0.0:8080', outputDir: './dist/', chainWebpack: (config) => { config.optimization .splitChunks(false); config .plugin('BundleTracker') .use(BundleTracker, [{ filename: … -
Set certain filter field
I have one innormal idea to get object through function and set to it certain field for filtering It will look as follows get_course(name='math') # or get_course(id=12) # and so on def get_course(**kwargs): for key, val in kwargs: return Course.objects.get(key=val) So is it possible to make this stuff? -
Object-level permissions in Django
I have a ListView as follows, enabling me to loop over two models (Market and ScenarioMarket) in a template: class MarketListView(LoginRequiredMixin, ListView): context_object_name = 'market_list' template_name = 'market_list.html' queryset = Market.objects.all() login_url = 'login' def get_context_data(self, **kwargs): context = super(MarketListView, self).get_context_data(**kwargs) context['scenariomarkets'] = ScenarioMarket.objects.all() context['markets'] = self.queryset return context But I want different users to see different sets of markets. For example, I want users from company X to only see markets pertaining to X, and same for company Y, Z, and so forth. Four possibilities so far, and their problems: I could hardcode this: If each user has a company feature (in addition to username, etc.), I could add a company feature to each market as well, and then use if tags in the template to ensure that the right users see the right markets. Problem: Ideally I'd want to do this through the Admin app: whenever a new market is created there, it would be specified what company can see it. I could try to use Django's default permissions, which of course would be integrated with Admin. Problem: Setting a view permission (e.g., here) would concern the entire model, not particular instances of it. From googling around, it … -
How to update user profil in django properly
i created a form to update a django profil, i use the default user model, when i submit the form and logout and i tried to login again, the new password is not working, but the old one is. this is my update view : def edit_profil_to_base(request): if not request.user.is_authenticated: return redirect('authentification') else: nom_profil_new = request.POST.get('nom_profil') nom_profil_old = request.user.username old_mdp = request.POST.get('old_mdp') # type: object new_mdp = request.POST.get('new_mdp') final_mdp = request.POST.get('final_mdp') mdp = request.user.set_password(new_mdp) if request.user.check_password(old_mdp) and new_mdp == final_mdp: User.objects.filter(username=nom_profil_old).update(username=nom_profil_new, password=mdp) logout(request) return redirect('authentification') the new_mdp and final_mdp are the new password and the confirmation of the password -
A function updating data and using the updated data again in one trial
I am working on a function that checks who submitted homework and calculate the penalty for those who didn't. Though it finely saves in db who did not submit homework, but a problem happens with the penalty. It is done in the same function (right after checking who handed in), but with old data. It does not get the updated data (+1 if not submitted). I think it is because the update and calculation are done all at once in one function, one trial. But I have no idea how to separate them or getting the updated data right. I made a function outside the original function that only calculates the penalty and applied in the original function, intending to separate two functions (checking submission and calculating penalty) but it resulted in the same. def group_update(request, group_id): group = get_object_or_404(Group, id=group_id) memberships = Membership.objects.filter(group=group) members = [x.person for x in memberships] Checking submission assignments = Assignment.objects.filter(done_checked=False, group=group, due_date__lte=datetime.now()) for assignment in assignments: submission = Done.objects.filter(assignment=assignment) submitters = [x.author for x in submission] assignment.done_checked = True assignment.save(update_fields=['done_checked']) for member in members: if member not in submitters: non_submit = memberships.get(person=member) non_submit.noshow_assign = non_submit.noshow_assign + 1 non_submit.save() Calculating penalty for membership in memberships: … -
I want to see the value when i press particular number button in django
I have a small Django calculator app. I want to display the value in the text box when any number button clicked My- HTML code <form action ="buttonClicked" method="POST"> {% csrf_token %} <div class="calculator"> <input type="text" class="calculator-screen" value="0" disabled name = "text-box"/> <div class="calculator-keys"> <button type="button" class="operator" value="+">+</button> <button type="button" class="operator" value="-">-</button> <button type="button" class="operator" value="*">&times;</button> <button type="button" class="operator" value="/">&divide;</button> <button type="button" value="7">7</button> <button type="button" value="8">8</button> <button type="button" value="9">9</button> <button type="button" value="4">4</button> <button type="button" value="5">5</button> <button type="button" value="6">6</button> <button type="button" value="1" name="b1">1</button> <button type="button" value="2">2</button> <button type="button" value="3">3</button> <button type="button" value="0">0</button> <button type="button" class="decimal" value=".">.</button> <button type="button" class="all-clear" value="all-clear">AC</button> <button type="button" class="equal-sign" value="=">=</button> </div> </div> </form> {% endblock %} My view.py from django.shortcuts import render from django.contrib import messages def calc(request): if request.method == 'POST': #here i want to take the button value and do some operation return render(request, 'Calculator.html') Calc if i press button 1 then it should display 1 in the text box... how can i do that? -
How to create custom user in django shell?
How can I create a custom user and set its password in django shell: I have this model: class CustomUser(AbstractUser): username = None email = EmailField(verbose_name='email address', max_length=255, unique=True, ) first_name = CharField(verbose_name='First Name', max_length=30, null=True, ) middle_name = CharField(verbose_name='Middle Name', max_length=30, null=True, blank=True, ) last_name = CharField(verbose_name='Last Name', max_length=30, null=True, ) phone_number = CharField(verbose_name='Phone Number', max_length=30, null=True, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email and I have this: from django.contrib.auth.base_user import BaseUserManager class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of username. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) I can create a superuser by this: python manage.py createsuperuser But I can not do … -
IntegrityError Primary Key Invalid (python-django)
I'm looking at a sentdex lesson and I have this error and why ? I saw a similar question here but couldn't get the answer from django.db import models from datetime import datetime # Create your models here. class tutorialcategory(models.Model): tutorial_category=models.CharField(max_length=200) category_summary=models.CharField(max_length=200) category_slug=models.CharField(max_length=200, default=1) class Meta: verbose_name_plural="Categories" def __str__(self): return self.tutorial_category class tutorialseries(models.Model): tutorial_series=models.CharField(max_length=200) tutorial_category=models.ForeignKey(tutorialcategory, verbose_name="Category", on_delete=models.SET_DEFAULT) series_summary=models.CharField(max_length=200) class Meta: verbose_name_plural="series" def __str__(self): return self.tutorial_series class tutorial(models.Model): tutorial_title=models.CharField(max_length=200) tutorial_content=models.TextField() tutorial_published=models.DateTimeField("date published", default=datetime.now()) tutorial_series=models.ForeignKey(tutorialseries, default=1, verbose_name="series", on_delete=models.SET_DEFAULT) tutorial_slug=models.CharField(max_length=200, default=1) def __str__(self): return self.tutorial_title Below is how the error looks like: django.db.utils.IntegrityError: The row in table 'main_tutorial' with primary key '1' has an invalid foreign key: main_tutorial.tutorial_series_id contains a value '1' that does not have a corresponding value in main_tutorialseries.id. -
django datepicker on datatable
I have to apply datepicker to my datatable to filter the data between two date range. I have applied my things and tried different codes but nothing worked out. My table contains date in the format( example- July 16,2019). I know it can be done by javascript but I am unable to do so. Please help. <table id="table table-mutasi" data-toggle="table" data-pagination="true" data-search="true" data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true" data-key-events="true" data-show-toggle="true" data-resizable="true" data-cookie="true" data-cookie-id-table="saveId" data-show-export="true" data-click-to-select="true"> <thead> <tr> <th data-field="state" data-checkbox="true"></th> <th data-field="id">center</th> <th data-field="cabin" >cabin</th> <th data-field="boooked_date">Booked date</th> <th data-field="release_date">Release Date</th> <th data-field="client">Client</th> <th data-field="booked_by">Booked by</th> {% if not request.user.is_superuser %} <th>Actions</th> {% endif %} </tr> </thead> <tbody> {% for object in object_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ object.premises}}</td> <td>{{ object.cabin }}</td> <td>{{ object.booked_date }}</td> <td>{{ object.release_date }}</td> <td>{{ object.client }}</td> <td>{{ object.booked_by }}</td> {% if not request.user.is_superuser %} <td> <a href="{% url 'manager:BookingUpdate' pk=object.id %}" style="color:black; margin-left:8px"><span class="glyphicon glyphicon-edit"></span></a> <input type="hidden" id="cendel" value="{{object.id }}"> <a href="#" style="color:black ;margin_left:8px;" id="delete" ><span class="glyphicon glyphicon-trash"></span></a> </td> {% endif %} </tr> {% endfor %} </tbody> </table> -
I don't know how to display formset in django
I don't know how to display formset individually. I understand how to display all at once. But I tried some model field names, but it didn't work. #views class UserEdit(generic.UpdateView): model = User form_class = forms.UserUpdateForm template_name = 'accounts/accounts_edit.html' success_url = reverse_lazy('accounts:edit') def get_object(self): return get_object_or_404(User, pk=self.request.user.user_id) #forms class ProfileUpdateForm(forms.ModelForm): class Meta: model = profile fields = ('first_name','last_name','birthday') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' ProfileFormSet = inlineformset_factory(User,profile,form=ProfileUpdateForm,extra=0) class UserUpdateForm(mixins.ModelFormWithFormSetMixin,forms.ModelForm): #Userモデルにprofileモデルを入れる formset_class = ProfileFormSet class Meta: model = User fields = ('username','email',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' #template <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.username.label_tag }} {{ form.username }} {{ form.email.label_tag }} {{ form.email }} {{ form.formset }} <button type="submit">Submit</button> </form> I want to specify and display instead of the method of displaying at once with formset. -
xml ParseError using mws with Django Python console but no error using same code/module-versions in system Python Console
I am using python-mws for Amazon. I have mws-4.4.1. It parses the xml documents from the mws api using the Python xml library. I can use the module successfully in a normal python script, but when I make a request through Django python manage.py shell I get the following traceback: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 250, in make_request parsed_response = DictWrapper(data, rootkey) File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 108, in __init__ self._mydict = utils.XML2Dict().fromstring(remove_namespace(xml)) File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 100, in remove_namespace return regex.sub('', xml) TypeError: cannot use a string pattern on a bytes-like object During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/xml/etree/ElementTree.py", line 1624, in feed self.parser.Parse(data, 0) xml.parsers.expat.ExpatError: syntax error: line 1, column 0 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "/app/amazon/amazon_mws.py", line 59, in parse_inventory_report report = self.reports.get_report(report_id=report_id) File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 422, in get_report return self.make_request(data) File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 253, in make_request parsed_response = DictWrapper(response.text, rootkey) File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 108, in __init__ self._mydict = utils.XML2Dict().fromstring(remove_namespace(xml)) File "/app/.heroku/python/lib/python3.6/site-packages/mws/utils.py", line 106, in fromstring text = ET.fromstring(str_) File "/app/.heroku/python/lib/python3.6/xml/etree/ElementTree.py", line 1314, in XML parser.feed(text) File "/app/.heroku/python/lib/python3.6/xml/etree/ElementTree.py", line 1626, in feed …