Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i solve HTTP Error 429: Too Many Requests?
Iam new to python and making a simple django app to download videos from youtube.It runs withou any error on local host but on production it throws an error : HTTP Error 429: Too Many Requests I know its sending too many request in short time but ho do i limit the request? -
Django 2.2 How to disable checkboxes in list view
Django 2.2 I have a list view controlled by admin.py class. No custom template, all default. I can control what fields from the table should be shown in the view with this: fields = ('myfield1','myfield2', ...). Each row in the list table has a checkbox in the first column: <td class="action-checkbox"> <input type="checkbox" name="_selected_action" value="123" class="action-select"> </td> My questions are: 1. How to disable those checkboxes ? 2. Can it be done for SOME of the checkboxes (let's say I have a list of pk ids for the rows I don't want to see checkboxes.) -
AttributeError: type object 'Product' has no attribute '_parler_meta' - DJANGO
When attempting to migrate my database in Django. I receive the following: Running migrations: Applying shop.0002_transactions...Traceback (most recent call last): File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/parler/models.py", line 942, in contribute_translations base = shared_model._parler_meta AttributeError: type object 'Product' has no attribute '_parler_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/migration.py", line 114, in apply operation.state_forwards(self.app_label, project_state) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/operations/models.py", line 86, in state_forwards list(self.managers), File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 96, in add_model self.reload_model(app_label, model_name) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 157, in reload_model self._reload(related_models) File … -
Default image being displayed even after uploading another picture in Django
I'm working on a website where users can post advertisements on houses they want to put up on rent. So I have an image field in models.py, but no matter which picture I upload, the system keeps displaying the default photo. I have set up the media root and url as per the documentation in my settings.py and also added it to my urls. models.py: class advertisements(models.Model): place=models.CharField(max_length=30) address=models.CharField(max_length=50) bedroom=models.PositiveSmallIntegerField() rent=models.PositiveIntegerField() size=models.PositiveIntegerField() date_posted=models.DateTimeField(default=timezone.now) owner= models.ForeignKey(User,on_delete=models.CASCADE) image = models.ImageField(default='defaulthouse.jpg',upload_to='house_pics') def get_absolute_url(self): return reverse('advertisement_details', kwargs={'pk':self.pk}) def save(self, *args, **kwargs): super().save(*args, **kwargs) image=Image.open(self.image.path) views.py: class AdvertisementCreateView(LoginRequiredMixin, CreateView): model= advertisements fields=['image', 'place','address','bedroom','bathroom','rent','size'] def form_valid(self, form): form.instance.owner=self.request.user return super().form_valid(form) urls.py: urlpatterns = [ path('', AdvertisementListView.as_view(), name='HomePage'), path('advertisements/<int:pk>/',AdvertisementDetailsView.as_view() , name='advertisement_details'), path('create_advertisements',AdvertisementCreateView.as_view(), name='create_advertisements'), path('your_advertisements',views.your_advertisements, name='your_advertisements'), path('advertisements/<int:pk>/update',AdvertisementUpdateView.as_view() , name='advertisement_update'), path('advertisements/<int:pk>/delete',AdvertisementDeleteView.as_view() , name='advertisement_delete'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html: <div class="container"> <legend class="border-bottom mb-4 text-center"><h3>House Information</h3></legend> <h5 class="card-title">Location: {{object.place}} </h5> <img src="{{ object.image.url }}" alt="..." class="img-thumbnail"> <p> Full Address: {{object.address}}</p> <p>Number of bedrooms: {{object.bedroom}}</p> <p>Number of Bathrooms: {{object.bathroom}}</p> <p>House/Apartment Size: {{object.size}} squarefeet</p> <p>Rent per month: {{object.rent}} taka</p> <legend class="border-bottom mb-4 text-center"><h3>Owner Information</h3></legend> <p>Owner Name: {{object.owner}}</p> <p>Advertisement Posted on: {{object.date_posted}}</p> {% if object.owner == user %} <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'advertisement_update' object.id%}">Update</a> <a class="btn … -
Error "the Content-MD5 HTTP header you passed for your feed did not match the Content-MD5 we calculated for your feed"
I am trying to set a maximum price for a product using Amazon API in a Django (Python) environment. I already solved the problem with calculating the md5 function which value is exactly the same as Amazon MWS Scratchpad calculates. After solving this issue, I get now a "the Content-MD5 HTTP header you passed for your feed did not match the Content-MD5 we calculated for your feed" error message. My code is as follows: feedTxt = '<?xml version="1.0" encoding="utf-8"?><AmazonEnvelope xsi:noNamespaceSchemaLocation="amzn-envelope.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Header><DocumentVersion>1.01</DocumentVersion><MerchantIdentifier>MERCH_ID</MerchantIdentifier></Header><MessageType>Price</MessageType><Message><MessageID>1</MessageID><Price><SKU>J1-1UKW-8Z03</SKU><MaximumSellerAllowedPrice currency="EUR">999</MaximumSellerAllowedPrice></Price></Message></AmazonEnvelope>' feed = open('myXml.xml', mode='w+', buffering=-1, encoding='utf-8') feed.write(feedTxt) feed.close() encodedFeed = feedTxt.strip().encode('utf-8') md5 = hashlib.md5(encodedFeed).digest() encodedMd5 = base64.b64encode(md5) parsedMd5 = urllib.parse.quote(encodedMd5, safe='') request_string = construct_strings(seller, '', 'SubmitFeed', '2009-01-01', args_dict) # this function defines the string to be signed and is working 100%, since I use it for all the other requests I do feed = open('myXml.xml', mode='r', buffering=-1, encoding='utf-8') myFile = {'file': feed} response = requests.post(request_string, headers = {'Content-MD5': encodedMd5, 'Content-Type': 'text/xml'}, files = myFile) feed.close() It's my first question asked here in stackOverflow. I appreciate any hints you can give me. Thanks! -
Django dropdown is not populated
I want my dropdown to get populated with values from one of my db tables in my Django project, yet it remains blank and I can't figure out why. This is my html code of my home.html page: <select name="regions" id="regions"> {% for item in regions_list %} <option val="{{ item.name_reg }}"> {{ item.name_reg }} </option> {% endfor %} </select> models.py: class data_reg(models.Model): id = models.AutoField(primary_key=True) name_reg = models.TextField(db_column='NAME_REG', blank=True, null=True) class Meta: managed = True db_table = 'reg' views.py: def MyView(request): regions_list = RegionChoiceField() query_results_dict = { 'regions_list': regions_list, } return render(request,'home.html', query_results_dict) forms.py: class RegionChoiceField(forms.Form): regions = forms.ModelChoiceField( queryset=data_immo.objects.values_list("name_reg", flat=True).distinct(), empty_label=None ) -
fitting a data file with multiple sample rows into single Django model object instance
I'll do my best to summarize, I'm working with cycling data from the Fit File format, which samples every second with power, heartrate, cadence. I'm currently getting the data into a dataframe and it's formatted like this and repeated over several thousand rows for however long I rode in seconds. {'watts': 176, 'heartrate': 59, 'timestamp': datetime.datetime(2020, 2, 26, 16, 19, 25), 'cadence': 80, 'time': 0.0}, {'watts': 176, 'heartrate': 59, 'timestamp': datetime.datetime(2020, 2, 26, 16, 19, 26), 'cadence': 80, 'time': 1.0} I can upload the file into my database model but the catch is that each second becomes its own object, when really each ride should be the object. I'm having a heck of a time trying to think through this, I've tried doing ArrayField and JSONField in the model, but get the following error, which I imagine is related to how the dataframe is put together: (psycopg2.errors.DatatypeMismatch) column "watts" is of type integer[] but expression is of type integer LINE 1: ...tts, heartrate, timestamp, cadence, time) VALUES (176, 59, '... ^ HINT: You will need to rewrite or cast the expression. Just curious for advice on how to construct the model and/or the dataframe to get the object appearing how … -
Django user record not found
I am trying to extend the user model in django by using a Client model (this might not be the ideal way, but that boat has sailed). When I try to access a user record in a template I get the error: No Client matches the given query models.py class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) views.py def update_client_details(request): if request.user.is_authenticated: user = request.user # print('pk', user.pk) client = get_object_or_404(Client, pk=user.pk) If I print the user.pk I see what I expect. Why doesn't it return an object? -
Using `select_related` with a table with composite primary key [Django]
Is there a way for Django to support composite primary key in combination of select_related or prefetch_related? I have a Records table with a composite primary key (device_id, created) with a schema like this (simplified): class Records(models.Model): class Meta: managed = False unique_together = (("device", "created"),) # The primary key is really (device_id, created) device = models.ForeignKey("hardware.Device", primary_key=True, on_delete=models.CASCADE) created = models.DateTimeField(db_index=True) value = models.FloatField(default=0) A record belongs to a Device, which is modeled like this (simplified): class Device(models.Model): car = models.ForeignKey("cars.Car", on_delete=models.CASCADE) last_record_at = models.DateTimeField(null=True, blank=True) I wish to run a query that will return a list of devices, but for each one also contain the last record. In theory, this would be something like that: Device.objects.filter(...).select_related("car", "last_record") But obviously "last_record" is not a foreign key, since Records contains a composite primary key which Django doesn't support. What would be the best way to do this, other than rewriting the query in raw sql? Is there a reasonable way to override select_related to handle composite keys? -
Django / React Cross-Origin Request Blocked Error hosted Google App Engine django-cors-headers not working
The application backend (django) and frontend (react) are hosted on google cloud at the same app. I've installed django-cors-headers and referred to it in settings.py: INSTALLED_APPS = ( ... 'corsheaders', ... ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_REGEX_WHITELIST = ( 'http://localhost:3000', 'https?\://myapp\.appspot\.com\/?', 'https?\://frontend-dot-myapp\.appspot\.com\/?', ) As far as I understood CORS_ORIGIN_ALLOW_ALL should already resolve this problem, but it doesn't, I just got a bit desparate there trying things out. CORS_ORIGIN_WHITELIST didn't work as well for me that's why CORS_ORIGIN_REGEX_WHITELIST. I haven't changed anything in this setup but now the Cross-Origin error appears. Since the last code change I installed django-silk to profile the app. Removing it doesn't appear to resolve the issue, so I'm not sure whether it's related. Help greatly appreciated! in requirements.txt: django-cors-headers==3.2.1 -
TypeError at /update_order/27 __str__ returned non-string (type NoneType)
Type Error when i am clicking on Update Update Button Image Models -
How to Add Clickable Table Of Contents to ReportLab with Python
I have spent the last few hours battling with this issue with ReportLab in Python I would like to add a Clickable TOC with Page numbering. Here is a visual of what I did so far: I just added them as basic text. I tried to create a class MyDocTemplate to hold the Table Of contents. class MyDocTemplate(BaseDocTemplate): def __init__(self, filename, **kw): self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) template = PageTemplate('normal', [Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')]) self.addPageTemplates(template) def afterFlowable(self, flowable): "Registers the Table Of Contents entries" if flowable.__class__.__name__ == 'Paragraph': text = flowable.getPlainText() style = flowable.style.name if style == 'Heading1': self.notify('TOCEntry', (0, text, self.page)) if style == 'Heading2': self.notify('TOCEntry', (1, text, self.page)) def addPageNumber(canvas, doc): """ Add the page number """ text = "FOOTER HERE" page_num = canvas.getPageNumber() text1 = "Seite %s" % page_num text2 = todaydate text3 = "COURTAGEMODELL POOL" text4 = "COURTAGELISTE" canvas.drawRightString(260*mm, 3*mm, text1) canvas.drawRightString(220*mm, 3*mm, text2) pdf_name = FileName1 + con + str(number1) + con + str(number2) + ext2 pdf_name2 = "Complete" + con + str(number1) + con + str(number2) + ext2 #--------------------------------------------------------------- heading1_style = ParagraphStyle(name = 'Heading1', fontSize = 16, leading = 16) heading2_style = ParagraphStyle(name = 'Heading2', fontSize = 12, leading = 14,) # … -
M2M relations not deleted after clear()
If a user is de-activated I want all memberships deleted. I thought this code in models.py would do it. But is doesn't, the relation is still there. class User(AbstractUser): membership_type = ManyToManyField(MembershipType, blank=True) .... def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.old_is_active = self.is_active def save(self, **kwargs): # Membership is cancelled if self.old_is_active is True and self.is_active is False: self.membership_type.clear() super(User, self).save() -
Problems with fixing navbar to top of page
For some reason when running the following code my navbar seems to be stuck in the middle of my screen. Based on other nav's i've made before it should be fixed to the top so i'm super confused. any help is appreciated! <body> <div class="container-fluid"> <nav class="navbar sticky-top navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <div class="navbar-nav align-items-center"> <a class="navbar-brand bigbrand" href="{% url 'post_list' %}">My Tech blog</a> <a class="nav-item nav-link" href="{% url 'about' %}">About</a> <a class="nav-item nav-link" href="https://www.github.com">Github</a> <a class="nav-item nav-link" href="https://www.linkedin.com">LinkedIn</a> </div> <div class="navbar-nav ml-auto"> {% if user.is_authenticated %} <a class="nav-item nav-link" href="{% url 'post_new' %}">New Post</a> <a class="nav-item nav-link" href="{% url 'post_draft_list' %}">Drafts</a> <a class="nav-item nav-link" href="{% url 'logout' %}">Log out</a> <a >Welcome: {{ user.username }}</a> {% else %} <a class="nav-item nav-link" href="{% url 'login' %}" aria-label="Login"> <span class="fa fa-user" aria-hidden="true"></span></a> {% endif %} </div> </div> </nav> </div> {# The actual blog posts#} <div class="content container-fluid"> <div class="col-md-8"> <div class="blog_posts"> {% block content %} {% endblock %} </div> </div> </div> {# SCRIPTS#} <script type="text/javascript" src="{% static 'js/blog.js' %}"></script> </body> </html> image of my output: -
Django-React-Framework localhost api endpoints on Safari not working
this is a wild shot because I cannot figure out why it doesn't work right. I have a Django-react-framework (DRF) and a React project running. Both of them work. However, when I make any request to the Python project I do so with Postman, just because it is more convenient to have any parameter defined in there. When doing so all requests work. The problem I face currently is is that any request I make from Safari doesn't work. Any request to my Backend from Safari just gives me this console error. Failed to load resource: A server with the specified hostname could not be found. 0.chunk.js:609 When I try the same with Chrome however it works all fine. That's why I don't think that it is because of my Backend. I added the settings.py anyways. Additionally, React on Safari works when I use the api-endpoints that are already hosted on the server. Further Information: when running on the server DRF server the api-endpoints with api., the app page with app. and the landing page on the root url. On localhost it only server the app on root this time, and the api-endpoints stay on api. """ Django settings for … -
Django Serializer Dataset Context
Is there a way to access the entire dataset that will be processed by the serializer before it does so. The Reason for this is because there is a bulk process I would like to do before I serialize the data. This is so that I can improve the performance of the serializing process to improve the delivery speed to the client(this is not required when creating only on retrieving) class MySerializer(serializers.ModelSerializer): def before_process(self, *args, **kwargs): # TODO: Some bulk work here with the self.full_unprocessed_dataset self.bulk_results = from_the_above_result def some_function_field(self): return self.bulk_results['some_key'] Is this possible? -
Django Site Can't Find Admin Styling or Media Files when Debug = False
I'm having trouble getting my django site running with debug = False. Info: Currently, Debug = False I am running on my local host I'm using Wagtail. But from what I've read, the problems I'm dealing with are more Django-related. Problem: When I go to the site on my local host, it can find static files, but it can't get any 'media' files.Example: GET http://127.0.0.1:8000/media/images/block-alphabet-abc.width-400.png Internal Server Error When I log into the admin panel, the look and feel is off in some places (like css components may be missing). When I go to edit a page, the look and feel is still off and the web developer tool has a bunch of 500 errors saying things like the http://127.0.0.1:8000/static/wagtailadmin/js/date-time-chooser.js?v=3a1ab45f is missing. What I have tried: I have ran python manage.py collectstatic. Doing that does not create the media directory though. It adds the wagtail admin files, but none of them have the little hash at the end. I tried running python manage.py compress, but I keep getting the error that none of the templates have the compression tag (which is true). I added logging, but I'm not sure how to resolve the errors. Question: How do I create the … -
JWT authentication using CBV
I have implemented a jwt in my project, some of my views are using apiview others are using cbv. currentely I moved the authentication system to jwt token authentication. my problem is, when I log in, the api views work as expected, but my cbv views are redirecting to the authentication page. In my settings I use sessionauthentication. 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ], but it still not working. can someone tell me if have a way to use boths views(apiview and cbv) knowing that authentication _classes is used only in drf? -
Django management commands reuse arguments
I want to write several management commands in a Django 2.2 and Python 3.8 project. All of these should have a --dry-run options. I would like to have some degree of code reuse in implementing these. What is the recommended approach? Here is how I'm doing it right now. Make MyBaseCommand extended from BaseCommand: class MyBaseCommand(BaseCommand): def add_arguments(self, parser): parser.add_argument('--dry-run', ....) class Command(MyBaseCommmand): def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_arguent('--other-arg', ...) Another option I've thought of is to create one or more decorators for each reusable arg, e.g. @dry-run, @yaml-output, @json-output etc. Then decorate the add_arguments method in each child class. This way I have more control over which management command gets which reusable arg. -
Django- Display columns depending on chosen filter in ModelAdmin (list_display)
I'm trying to show different columns(in list_display) depending on chosen filter. Here is my code: # Filter: class FilterNameFilter(admin.SimpleListFilter): title = ('FilterName') parameter_name = 'FilterName' def lookups(self, request, model_admin): return ( ('xxx', _('xxx 1')), ('yyy', _('yyy 2')), ) def queryset(self, request, queryset): if self.value() == 'xxx': return queryset.filter(c__isnull=False) if self.value() == 'yyy': return queryset.filter(d__isnull=False) # Model: class pricelist_admin(ModelAdmin): ... list_display = ('EAN_id', 'Vendor', 'Description', 'DynamicColumn', 'a', 'b', 'c', 'd', 'e') list_filter = ('Vandor_id__Name', FilterNameFilter) search_fields = ('EAN_id__Description', 'EAN_id__EAN') #Dynamic column: def DynamicColumn(self, obj): if # ... Here is my code for showing different columns, # it works fine for other loop's examples, but I don't know # how to integrate it with "FilterNameFilter" to return desired columns: return obj.e else: return obj.EAN.Description Any ideas? Help would be really appreciated! -
How to filter children by parent field
Example, models.py: class Guy(models.Model): name = models.CharField(max_length=30) class Mom(models.Model): name = models.CharField(max_length=150, choices=MOTHER_NAMES, default=MOTHER_NAMES[0][0]) guy = models.OneToOneField(Guy, on_delete=models.SET_NULL) How to get queryset of Guys whose Mom's name is 'Sophia' -
What is the best and up to date Django authentication library as of 2020?
Our project is entirely on Django Rest Framework, so the ftont-end user interface features of Django are not used. The front-end is on ReactJS. When you mention the method that you suggest, please say why, and whether you used it recently in a project or a company. Many thanks for the help. -
How to display average per grading period in html? using django
I have this filter that compute the final average per Grading Categories gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True))\ .filter(grading_Period__in=period.values_list('id', flat=True)).values('Grading_Categories').annotate(average_grade=Avg('Grade')) when i print it, the result is like this: <QuerySet [{'Grading_Categories': 1, 'average_grade': 88.3333333333333}, {'Grading_Categories': 2, 'average_grade': 90.0}]> I just want to display in my html the actual average per grading period in html but the result i got in html is like this <QuerySet [{'Grading_Categories': 1, 'average_grade': 88.3333333333333}, {'Grading_Categories': 2, 'average_grade': 90.0}]> -
Is there a way to serve a file in django that is generated in a Thread?
I'll explain myself. In my Django web I have a button that calls a view. #The view that's being called def pil_image(request, pdv_id): fp=FileProcesor(request,pdv_id) th = threading.Thread(target=fp.process) th.start() messages.success(request,"The file is being generated, when it's ready you'll be able to download it") return redirect('punto-de-venta',pdv_id) The FileProcesor class has a method process that generates a zip file. The problem is that sometimes this file takes too much time to process. Thats why I create the file in a Thread. But once the file is ready I cant redirect the user to the file. I want that when the file is ready automatically the "standar downloading pop up" shows to the user. if I use this code instead the download message shows but the web is "frozen" untill the file is created. def pil_image(request, pdv_id): fp=FileProcesor(request,pdv_id) return fp.process() -
How to fix TypeError: initial_value must be str or None, not bytes using StringIO
I've got the error message initial_value must be str or None, not bytes and i do not know how to fix it. I face with that after changing to python 3. Moreover I change the import to from io import StringIO Here is my code : def render_to_pdf(template_src, context_dict): template = get_template(template_src) context = context_dict html = template.render(context) result = StringIO() pdf = pisa.pisaDocument(StringIO(html.encode("utf-8")), dest=result, encoding="utf-8") Here is the Traceback: Environment: Request Method: GET Request URL: http:///pdf/11479/ Django Version: 2.2.6 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'bootstrap_themes', 'intranet', 'crispy_forms', 'fm', 'dal', 'dal_select2', 'django_crontab', 'django_tables2', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/var/www/vhosts/intranet.health-nutrition.gr/health_nutrition/intranet/views.py" in pdf_view 598. 'fpa_total':fpa_total(), File "/var/www/vhosts/intranet.health-nutrition.gr/health_nutrition/intranet/views.py" in render_to_pdf 542. pdf = pisa.pisaDocument(StringIO(html.encode("utf-8")), dest=result, encoding="utf-8") Exception Type: TypeError at /pdf/11479/ Exception Value: initial_value must be str or None, not bytes Any idea how to fix it?