Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ProgrammingError at /admin/aws_app/imageframe
django.db.utils.ProgrammingError: column "frame_captype_id" of relation "aws_app_imageframes" does not exist LINE 1: ...ws_app_imageframes" ("time_stamp", "image_frame", "frame_cap... I recently truncated this table ( image frames which is having foreign-key relation with frame_cap, but now it is not allowing me to push any data , and throwing the above error , what's the issue ?, currently both the tables are truncated class ImageFrames(models.Model): time_stamp = models.DateTimeField(auto_now_add=True) image_frame = models.FileField(upload_to = 'camera_frames',null=True,blank=True,max_length=500) flagged_as = models.ManyToManyField(FLag) frame_captype = models.ForeignKey(FrameCapType,on_delete=models.CASCADE,null=True,blank=True) -
Behave Django Testing - Behave testing with selenium only uses dev database instead of test
I am sorry I am very new to the world of Django Behave testing, and cannot find any resources online regarding the question I have: How to properly set up behave django so that it can use selenium to test with a test database loaded with test fixtures? I am trying to write an integration test that will test a simple permission feature, where the user can log in and the response will contain an auth_token that subsequent pages will use to either block or allow depending on the user. The test user is loaded with a test-users.json fixture, but when running behave tests, I get 400 (incorrect credentials) on my dev server and I cannot log in using selenium. I can only log in with a user that is currently present in my dev database. This makes me think that either my fixtures aren't loaded, or that selenium isn't using the test database that was setup by behave? Here are parts of my givens.py, evironment.py setup and my settings.py # tests/acceptance/environment.py from rest_framework.test import APIClient from seleniumrequests import Chrome import os os.environ['DJANGO_SETTINGS_MODULE'] = 'core.settings.settings' def django_ready(context): context.test.client = APIClient() context.browser = Chrome() context.browser.implicitly_wait(1) context.server_url = 'http://localhost:8000' context.fixtures = [ … -
How to avoid having django template display before VueJS render
I have a Django template that I'm trying to render with VueJs using CDN. The problem is when the page is loaded, i see the raw code of django with the delimiters before it get rendered with VueJS. It takes less that a sec. I have an API call (using Fetch) that retrieve some data before displaying them and I put that in mounted() function. The delay is almost 0.6sec and we can see Django render before vuejs render the page. Then I change mounted() to beforeMount(). I now see the django render from time to time but it's much better because often, vue render comes first. My question is, is there a better way to solve this. I'm using CDN and I'm didn't want to get intot server side rendering for this project. Thanks -
Are these HTML files properly configured for user.is_authenticated method in Django
I intend to have extremely sensitive information within my Django website. This being said, I need to restrict access to user accounts only. Is this a proper configuration for securing my HTML files and sensitive data to the rest of the world? Django file structure: I also have my normal HTML files at the templates level. login.html: <html lang="en"> <head> <meta charset="UTF-8"> <title>Login In</title> </head> <body> <form method="POST" style="text-align:center;font-family:verdana;" > {% csrf_token %} {{ form }} <button type="submit">Login</button> </form> </body> </html> base.html <!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>Search</title> <link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}"> </head> <body> {% if user.is_authenticated %} {% block content %} {% endblock %} {% else %} <h1 style="text-align:center;">Login <a href="/login" style=";text-decoration:underline;">Here</a></h1> {% endif %} </body> </html> example.html <!DOCTYPE html> {% load static %} {% extends "base.html" %} {% if user.is_authenticated %} {% block content %} <html> <head> <title>Example</title> </head> <h1>Example!</h1> <p class='text'>Hello World</p> </html> {% endblock %} {% else %} <p>Login <a href="/login">Here</a></p> {% endif %} -
How to create a subtraction in the inventory when a order is made? [Django] [Python] [E-commerce website]
I’m a python/django begginer. I decided to build a e-commerce website using django for an academic project. I’ve been able to develop enough of the project and build understanding of the subject, but right now I’m having issues finding a way to subtracts the number of items listed in the inventory whenever a order is made. That’s the code for the models, evey product has it's own stock quantity call inventory: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() description = models.TextField(default='', null=True, blank=True) digital = models.BooleanField(default=False,null=True, blank=True) image = models.ImageField(null=True, blank=True) inventory = models.IntegerField(default=0) def __str__(self): return self.name def has_inventory(self): return self.inventory > 0 This is the code I made to subtract base on quantity of the item ordered, but I can’t make it work, it won’t subtract the number of items from the inventory on the product stock. class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.product) + " x " + str(self.quantity) def inventory(self): product.inventory = self.inventory product.inventory -= int(self.quantity) return inventory What could I do to make it work? -
CORS blocks connection between Flutter and Django API
I want to connect Djnago API with flutter app, but I have lots of problem. I'll show flutter and django code both. Settings.py """ Django settings for crawler project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)4%#q5&d3^5=0!bauz62wxmc9csk*_c09k!jl2g1a-0rxsa--j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawling_data', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] ROOT_URLCONF = 'crawler.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'crawler.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': … -
How to paginate a pandas dataframe on django based on columns
I have a cvs with more than 40000 columns and I need to separate it on parts so the user only can see some columns by pages and reduce the load time, I think on pagination but the references only works for rows, How can I use it to separate the columns? It's that posible? I'ts a csv converted on a Dataframe with pandas -
JS file does not work when trying to use it by '<script src='
I've been practicing JavaScript, and I am trying to create a simple notification system using Django. However, when I try to serve my JS file, it does not work. I mean, it does not show up 404 error. Here's my code (client): console.log("called") emitData = { "user_id": current_user_id } console.log("send notification request") socket.emit("requestExistingNotifications", emitData) socket.on("newNotification", (data)=>{ // ... }) socket.on("notificationHistoryFromServer", (data)=>{ // still writing }) Here's my html file: {% load static %} <script src="{% static 'js/notification.js' %}"></script> When I tried to put my code in script tag directly, it works just fine, so I know that my server-side code is fine. However, I want to put the JS code in another file. -
can someone guide me on the use case for serving media files via uploadcare vs amazon S3 vs other solutions?
I am trying to make a django application (with the Rest framework) and I was just researching and came across different ways to serve media files. what is the recommended approach for a project/app that lets you upload pictures so that other users can download them? I came across CDN such as uploadcare, cloudinary and then ofcourse amazon S3 as well. Is there a difference in using these services like uploadcare vs S3 in terms of speed or scaling? thanks in advance, -
Django Webmanifest
I'm building a PWA in Django. The serviceworker is located in pwa->static->pwa->sw.js Everthing gets loaded/cached and the serviceworker is running. If in manifest.json "start_url": "/" or "start_url": "/pwa" is set, i get this serviceworker not found error, from the manifest, so it's not installable, but if I set it to "start_url": "." i can install my App but then I get: Directory indexes are not allowed here. Request Method: GET Request URL: http://127.0.0.1:8000/static/pwa/ At app startup. How can i overwrite or redirect this request to http://127.0.0.1:8000/pwa/ ? -
python3 ModuleNotFoundError: No module named 'celery'
I import celery from python but it through error from celery import Celery line 1, in <module> from celery import Celery -
DRF create instance with nested serializer raising exception on serializer.is_valid
Contextualization I have the following serializer that that has a nested serializer to return the user username instead of the id class RoomSerializer(serializers.ModelSerializer): participants = ParticipantSerializer(many=True) # Nested serializer class Meta: model = Room fields = '__all__' I crated the following ListView under this url => `localhost:8000/api/rooms/<username>/` class RoomList(generics.ListCreateAPIView): serializer_class = RoomSerializer def get_queryset(self): return Room.objects.filter(participants__username=self.kwargs['username']) def create(self, request, *args, **kwargs): print(request.data) return super().create(request, *args, **kwargs) First issue The first thing that happened was that I sent the following data data = { 'participants': ['foo', 'foo1'] } and returned error 400 with the following data {"participants": [ {"non_field_errors": ["Invalid data. Expected a dictionary, but got str."]}, {"non_field_errors": ["Invalid data. Expected a dictionary, but got str."]} ] } So I changed the request data to look like the payload when I make a get request to this endpoint. data = { 'participants': [ {username: 'foo'}, {username: 'foo2'}, ] } Second issue Still returning code 400 with this response. {"participants": [ {"username": ["A user with that username already exists."]}, {"username": ["A user with that username already exists."]} ] } what I need On 'GET' I need list of all rooms that a user is a participant and each room should have a … -
Special Characters Menu in Wagtail Editor
I am trying to add a menu of special characters in the wagtail editor so that users can add a menu of selected special characters to the content. What is the best way to do this? I can't find any plugins on this page either: https://wagtail.io/packages/. -
Django / GeoDjango can't find the GDAL library on Ubuntu / Dokku
We're getting "django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library", GeoDjango's common installation issue. Dev environment is Win10 and GDAL libraries were resolved following this answer on the same question for windows, which supplies filepaths directly. I now can't deploy because prod is Ubuntu 20.04 and that answer doesn't address how to resolve on Ubuntu. I'm new to Ubuntu / Linux and I think I've installed GDAL with sudo apt install libpq-dev gdal-bin libgdal-dev following these instructions, but Django doesn't know how to find the libraries nor do I. This question mentions "GDAL_LIBRARY_PATH = '/usr/local/lib/libgdal.so.1.15.1'", but my "/usr/local/lib/" only includes the dirs of python3.8 and 3.9. Also, unsure if relevant but I'm deploying on Dokku, and am unsure if containerizing things precludes Django from finding libs outside of Dokku's fancy ecosystem I don't well understand. This post is the only other post mentioning both Dokku and GDAL, and although it asks something unrelated its requirements.txt includes "GDAL==2.4.1". Could we somehow resolve this by supplying it in a similar way? What simple thing am I missing or doing wrong? -
Django Cannot auto focus on this form but can on forms
I have a login, register and password reset pages both login and register pages auto focus on the username field however on my password reset page auto focus is not working. I have tried widget_tweaks within my template but to no avail like so: {{ fieldValues.email|attr:"autofocus" }} and {{ form.email|attr:"autofocus" }} I just cannot get my head around why auto focus works on my other forms but not on password reset. My code is as follows: View class RequestPasswordResetEmail(View): @method_decorator(check_recaptcha_form) def get(self, request): return render(request, 'password/reset-password.html') @method_decorator(check_recaptcha_form) def post(self, request): email = request.POST['email'] context = { 'values': request.POST } current_site = get_current_site(request) user = User.objects.filter(email=email) user_by_email = User.objects.filter(email=email).first() if not user.exists(): messages.error(request, 'Please supply a valid email') return render(request, 'password/reset-password.html', context) if user.exists() and request.recaptcha_is_valid: uid = urlsafe_base64_encode(force_bytes(user_by_email.pk)) token = PasswordResetTokenGenerator().make_token(user_by_email) email_subject = 'WFI Workflow System - Password Reset' email_body = 'password/password_reset_email.html' to_email = [user_by_email.email] send_email(user, request, email_subject, email_body, uid, token, to_email) messages.success( request, mark_safe( 'We’ve emailed you instructions for setting your password, if an account exists with the email you entered. You should receive them shortly.' '<br class="brmedium"> If you don’t receive an email, please make sure you’ve entered the address you registered with, and check your spam folder.</br>')) … -
Use CreateView and ListView in the same template and use form.instance correctly
In my project my user should be able to submit an appointment (class UserAppointment) based on the disponibility given by the staff (class StaffDuty). So I'd ike to use the CreateView Class of the UserAppointment model and ListViewClass for the StaffDuty model in the same template. With my code I can access the data from the StaffDuty model but I'm not able to submit the form for UserAppointment model, since the submit button does nothing. Also I'd like to automatically assign the staff and event foreing key and pass data from StaffDuty to complete form.instance.date_appointment with the date given in the staff model and form.instance.event_name with the name of the event that is found in the Event model. But my code is not working at all models.py class Event(models.Model): name = models.CharField(max_length=255) staff_needed = models.PositiveIntegerField() date = models.DateField() spots_total = models.PositiveIntegerField() venue = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('event_details', args=[str(self.id)]) class StaffDuty(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) date_work = models.DateField() shift = models.CharField(max_length=255) def __str__(self): return self.event.name | str(self.date_work) class UserAppointment(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) staff = models.ForeignKey(StaffDuty, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) event_name = models.CharField(max_length=255) date_appointment = models.DateField(null=True) morning_hour = models.CharField(max_length=255) afternoon_hour = … -
HEROKU: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)')
I am having an issue trying to use mssqlserver with pyobdc in django on heroku. I'm getting this error:('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)') -
NoReverseMatch at /create_blog/ Reverse for 'update_blog' with no arguments not found. 1 pattern(s) tried: ['update_blog/(?P<id>[0-9]+)$']
ERROR views.py urls.py link_to_update PLEASE TYPE THE CODE DOWN AND TELL THE REASON AND PLEASE SEND IT -
how to use group by in django with TruncDay
I'm trying to show profit and loss of a company using group by for each day here is what i tried : class InvoiceItem(models.Model): item = models.ForeignKey(Item,on_delete=models.CASCADE) invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE) quantity = models.IntegerField) price = models.DecimalField(max_digits=20,decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) class Item(models.Model): item = models.ForeignKey(Information,on_delete=models.CASCADE) quantity = models.IntegerField() buying_price = models.DecimalField(max_digits=30,decimal_places=2) cost = models.DecimalField(max_digits=30,decimal_places=2,blank=True,null=True) i have to show daily profit with daily loss , something like this total_price = 1000 , total_main_price = 900 , profit = 100 but if we have sell something for example its main_price is 100 but we sell it for 90 , then our profit will change to 90 and we dont have loss because still we have profit , but i want to show its loss as well even if we have profit in most of invoices but in one invoice we have loss , i have to show the loss of that invoice ! i dont want to show the average i just want to show summation of profit invoices and loss of invoices separately class DailyInvoiceIncomeView(LoginRequiredMixin,ListView): template_name = 'invoiceapp/dmyincomes/dailyinvoice.html' model = InvoiceItem def get_queryset(self): return InvoiceItem.objects.annotate(day=TruncDay('created_at')).values('day').annotate( paid_price=Sum( (F('price') * F('quantity')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)), storage_price=Sum( (F('item__buying_price')+F('item__cost')) * F('quantity'),output_field=DecimalField(max_digits=20,decimal_places=3)), income=Case( When(paid_price__gte=F('storage_price'),then=F('paid_price')-F('storage_price')),default=0,output_field=DecimalField(max_digits=20,decimal_places=3)), ).annotate( loss=Case( When( storage_price__gt=F('paid_price'),then=F('storage_price') - … -
'NoneType' object is not subscriptable . When using the django admin
I am trying to create an ecommerce website and when working to make the cart order for non authenticated users and then save it and send it to the backend I just get this error in every view when I log in the django admin panel. It works well when I am not logged as an admin although it does not save the order once the order is set to completed. The error is 'NoneType' object is not subscriptable. and mentions this variable as empty: cartItems = data['cartItems'] views.py from django.shortcuts import render from .models import * from django.http import JsonResponse import json import datetime from .utils import cartData, cookieCart def store(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {'products':products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems': cartItems} return render(request, 'store/cart.html', context) def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems': cartItems} return render(request, 'store/checkout.html', context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('ProductId:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, … -
Queryset filter() in Django with ForeignKey
I'm having trouble with Django queryset. First of all, what I want to do is to receive from the customer which discount coupons (dc for short) he/she used and then compare with the ones already in the system. And I did manage to do it with 1 my view: @login_required(login_url='login') def cupons(request): produtos = Produto.objects.all() cliente = Cliente.objects.get(user=request.user) pedido = Pedido.objects.all().get(cliente=cliente) return render(request, 'cupons.html', {'lista': produtos, 'venda': pedido.produto.cupom}) The succesfull result P.S: There are 2 Usado (Used) because they have the same "dc" The problem starts when the user used 2 or more "dc", it says that get() received more than 1 result and after some research I found that I need to use filter, but someone can explain me how can achieve the same result using filter ? My classes are Cliente (Client), Produto (Product) and Pedido (Order). my model: class Cliente(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... class Produto(models.Model): STATUS = ( ('Novo', 'Novo'), ('Expirado', 'Expirado'), ('Usado', 'Usado'), ) ... ... cupom = models.CharField(max_length=200, null=True) ... class Pedido(models.Model): cliente = models.ForeignKey(Cliente, null=True, on_delete=models.SET_NULL) produto = models.ForeignKey(Produto, null=True, on_delete=models.SET_NULL) ... Just for sure my html: {% for i in lista %} <tr> <td ><img src="{{i.lojista.imagem}}" class="logo_lojista"> </td> <td> {{i.nome}}</td> <td><a … -
How can I use a Local SQLite3 DB for Testing and a MSSQL DB for Production in Django?
So I have a project I'm currently working on where my DB user does not have the ability to create and destroy databases on the server where my production DB is stored. So I have decided to try and locate my test databases within sqlite3 database much like is shipped with Django. I tried doing this which I think I read about somewhere in the Django documentation, but it is not working and keeps giving me the error: AttributeError: 'PosixPath' object has no attribute 'startswith' Code: DATABASES = { # C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\DATA 'default': { 'ENGINE': 'engine', 'NAME': 'db', 'HOST': '1.1.1.1', 'PORT': '1', 'USER': 'username', 'PASSWORD': 'password', 'OPTIONS': { 'driver': 'driver', 'connection_timeout': 15 }, 'TEST': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'testdb.sqlite3', 'HOST': 'localhost' } }, } I feel like I'm close and so I tried removing the BASE_DIR and just going with the file name but that still sends me messages saying that the user does not have the ability to create DB in master which means it's still connecting to the same PRODUCTION server. -
trying to migrate a date of birth field and i keep getting column "date_of_birth" of relation "Occupier_occupier" does not exist
class OccupierManager(BaseUserManager): def create_user(self,email,username,date_of_birth,occupations,password=None): if not email: raise ValueError('Users must have email address') if not username: raise ValueError('Users must have username') if not occupations: raise ValueError('Occupiers must have occupation') if not date_of_birth: raise ValueError('Users must enter date_of_birth') user = self.model( email = self.normalize_email(email), username =username, occupations = occupations, date_of_birth = date_of_birth ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email = self.normalize_email(email), password=password ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user #Occupier model class Occupier(AbstractBaseUser): email = models.EmailField(verbose_name='email',max_length=59, unique=True) username = models.CharField(max_length=30,unique=True) occupations = models.CharField(max_length=200,null=False) #amount of occupations user does #cliques = models.ForeignKey(Clique,null=True,on_delete=models.CASCADE) #cliques user is in date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) date_of_birth = models.DateField(default=None,null=False) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) password = models.CharField(max_length=255,unique=True) objects = OccupierManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','occupations','password'] def str_(self): return self.username def has_perm(self,perm, obj=None): return self.is_admin def has_module_perms(self,app_label): return True -
failing to install a package in virtual enviroment
Im trying to install django in my virtual environments but files always get install in the python main direction (im using python latest version (3.10) and pip (21.3.1) and visual studio code) too and also when iim trying to work with my new venv i have issues with imports django -
Lack of correct display of Persian in PDF format in Django
I used reportlab in Django to make a pdf of Persian words in Django as follows: from reportlab.pdfgen import canvas from reportlab.lib.units import inch from reportlab.lib.pagesizes import letter import io from django.http import FileResponse from django.conf import settings import reportlab def pdf(request): reportlab.rl_config.TTFSearchPath.append(str(settings.BASE_DIR) +'/static') pdfmetrics.registerFont(TTFont('Samim','Samim.ttf')) buf=io.BytesIO() c=canvas.Canvas(buf,pagesize=letter) txt=c.beginText() txt.setTextOrigin(inch,inch) txt.setFont('Samim',14) lines=[ 'سلام', 'خوبی', 'چه خبر' ] for l in lines: txt.textLine(l) c.drawText(txt) c.showPage() c.save() buf.seek(0) return FileResponse(buf,as_attachment=True,filename='me.pdf') But the output is as follows: I also used other fonts like Nazanin but the result did not change and I even used the xhtml2pdf library but the result was still in this format. In fact, there is a problem with the output format, which must be right to left, which is left to right, unfortunately! How should I solve this problem?