Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Download Image created from Pillow using Django
I am creating image using Pillow from text input provided by user. I am using Django and django-ninja to process the data and then send the image to user. It will not show the image and my server will not store the image, the user will get to download the image. The process will be like: User type text > User press Download button > Ajax send text to Django backend > Django backend using Pillow create image based on the text > User download the image There is no error but I am not able to download the image. This is my Ajax: function downloadDoa(){ allDoas = [] for (let i = 0; i < userDoaAll.length; i++) { userCustomMadeDoa = userDoaAll[i]; if (userCustomMadeDoa.classList.contains("customUserDoa")){ allDoas.push(['na',userCustomMadeDoa.innerHTML]) } } console.log(allDoas) $.ajax({ url: "{% url 'api:download_doa' %}", data: { customDoasLists: JSON.stringify(allDoas), csrfmiddlewaretoken: '{{ csrf_token }}', }, method : "post", dataType : "json", headers: {'X-CSRFToken': csrftoken}, mode: 'same-origin', // Do not send CSRF token to another domain. csrfmiddlewaretoken: '{% csrf_token %}', success: function (response) { console.log(response) }, }); } This is from my api.py to process user input: @api.post("/download_doa",url_name="download_doa",auth=None) def download_doa(request): text_list = json.loads(request.POST.get('customDoasLists')) font_path_a = "Hafs.ttf" font_path_na = "Arial.ttf" font_size_a = 40 font_size_na … -
Django "The process cannot access the file because it is being used by another process" error while trying to delete a videofile
My Post model has relation to a PostMedia model, which can contain images and videos. I have no trouble with deleting images, but when I try to delete video, I face this error: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process. Generally speaking, I have no idea about the reason it happen. Maybe, someone face the problem? models.py class Post(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE ) title = models.CharField( max_length=200, null=True, blank=True, help_text="Beauty header to start your post." ) body = CharField( max_length=500, help_text='Required.' ) other_file = models.FileField( null=True, blank=True, upload_to="posts/files", help_text="Only .rar, .zip and .pdf files accepted!", validators=[ FileExtensionValidator(allowed_extensions=['rar', 'zip', 'pdf']) ], ) post_date = models.DateTimeField( auto_now_add=True ) likes = models.ManyToManyField( User, through='UserPostRel', related_name='likes', help_text='Likes connected to the post', ) class PostMedia(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='post_media', ) file = models.FileField( upload_to="posts/post_media", validators=[], ) file_thumbnail = models.FileField( upload_to="posts/post_media/thumbnails", null=True, blank=True, ) servername = models.CharField( max_length=255 ) views.py class PostCreateView(AuthRequiredMixin, SuccessMessageMixin, View): template_name = 'create_post.html' model = Post form = PostCreationForm success_url = reverse_lazy('index') success_message = _('Post created successfully') def get(self, request, *args, **kwargs): form = self.form() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form(request.POST, … -
Django DRF save data for every session (logging user)
I want when a user logins save some data like email, name and ids while the user is logging in And I can get the data anywhere like models.py ## views.py def post(self, request): print('------------login request----------------') serializer = self.serializer_class(data=request.data, ) if not serializer.is_valid(): return api_response(error={"non_field_errors": "Unable to log in with provided credentials"}, status=ApiStatus.fail) user = serializer.validated_data['user'] account_serializer = AccountSerializer(user) token, created = Token.objects.get_or_create(user=user) token = token.key data = account_serializer.data data.pop('password', None) data['token'] = token request.data['account_id'] = user.pk device_serializer = DeviceSerializer(data=request.data) if device_serializer.is_valid(): device_serializer.save() # Save data here like data['db_key'], data['email'] return api_response(data=data) ## models.py from django.db import models class User(models.Model): ## and get data here => data['db_key'] objects = models.Manager().using() -
How to edit Django Crispy field names
I'm trying to edit field names that come with (probably) crispy forms but I cannot find the file anywhere. This is my post_form.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Post</legend> {{ form.media }} {{ form|crispy }} </fieldset> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} I tried to find it from inspect I did find where I wanna change but when I search that file in my project I cannot find it anywhere. I want to change this Content* to Body -
Virtual environment installing packages globally
I have been working on a Django project, which I created and have been running in a virtual environment. I recently made the project folder a GIT repository and pushed the project up to Github. The next time I went to run the development server I got an error message saying that Django wasn't installed. Whilst in the virtual environment I used pip to install Django in my project folder however it is being installed globally and I can run the server outside the virtual environment. I have uninstalled Django and tried again to install it in the virtual environment, however it is still installing globally. (venv) C:\Users\tomge\django_projects\djangodelights>pip uninstall Django Found existing installation: Django 4.1.7 Uninstalling Django-4.1.7: Would remove: c:\users\tomge\appdata\local\programs\python\python310\lib\site-packages\django-4.1.7.dist-info\* c:\users\tomge\appdata\local\programs\python\python310\lib\site-packages\django\* c:\users\tomge\appdata\local\programs\python\python310\scripts\django-admin.exe Proceed (Y/n)? y Successfully uninstalled Django-4.1.7 (venv) C:\Users\tomge\django_projects\djangodelights>py -m pip install django Collecting django Using cached Django-4.1.7-py3-none-any.whl (8.1 MB) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\tomge\appdata\local\programs\python\python310\lib\site-packages (from django) (0.4.3) Requirement already satisfied: tzdata in c:\users\tomge\appdata\local\programs\python\python310\lib\site-packages (from django) (2023.3) Requirement already satisfied: asgiref<4,>=3.5.2 in c:\users\tomge\appdata\local\programs\python\python310\lib\site-packages (from django) (3.6.0) Installing collected packages: django Successfully installed django-4.1.7 WARNING: You are using pip version 22.0.4; however, version 23.0.1 is available. You should consider upgrading via the 'C:\Users\tomge\AppData\Local\Programs\Python\Python310\python.exe -m pip install --upgrade pip' command. … -
How can I edit the message of the email sent by Wagtail when a page is submitted for moderation?
I'm trying to edit the content of the email sent by Wagtail when a page is submitted for moderation, I've dug into the Wagtail source code and it turns out there is a function called send_mail which actually sends the emails to all the subscribers when a page is sent for moderation, this function is called by another one called send_notification which takes some notification templates (HTML and txt files) depending on the type of action (submitted, approved, rejected) of the page, those templates contain the email content and I haven't found the way to override the content of those templates from my Wagtail project. If someone has done that before, I really appreciate your help. Thank you! I'm expecting being able to edit the content of the emails because I want to add some custom fields like comments. -
Auto pre-fill form Django
How to pre-fill form fields in Django. What would be the pre-filled data from the User class when forming the order form. The result need like this: my view def order_create(request): cart = Cart(request) user = request.user if request.user.is_authenticated: if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save(commit=False) if cart.coupon: order.coupon = cart.coupon order.discount = cart.coupon.discount order.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) cart.clear() order_created.delay(order.id) request.session['order_id'] = order.id return redirect(reverse('payment:process')) else: form = OrderCreateForm() else: return redirect('login') return render(request, 'orders/order/create.html', {'cart': cart, 'form': form}) my form class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ['first_name', 'last_name', 'email', 'address', 'postal_code', 'city'] my teplate <form action="." method="post" class="order-form"> {{ form.as_p }} <p><input type="submit" value="Place order"></p> {% csrf_token %} </form> Im try to use initial but with no result. -
Django Equivalent of JSDocs?
I've been tasked to add an automated endpoint documentation tool for our Django codebase. It needs to produce html files that we can then host in our s3 buckets for internal reference. I thought drf-spectacular would be it, but it doesn't seem to actually produce html files, but only documentation for one's local environment. Is there a tool or library that can do this? Something like JSDocs or TypeDoc, where I can run a command, and dump html documentation files into an s3 bucket. Thank you! -
Django Select2 Widget bad rendering?
I tried to implement multi select-boxes from select2. The widget works fine, but the user input is under the field. Screen: enter image description here this how it looks in html. <select class="js-example-basic-multiple" name="states[]" multiple="multiple"> <option value="AL">Something</option> <option value="WY">Wyoming</option> <option value="WY">Somebody</option> </select> <script> $(document).ready(function() { $('.js-example-basic-multiple').select2(); }); </script> I tried to change height, but maybe not its the problem -
Missing table socialaccount_socialapp_sites, how do I fix this?
Whenever I try to add a social app, I get an error that the table socialaccount_socialapp_sites is missing. I had some set up problems because I forgot to include django.contrib.sites at first, but after fixing that I seem to get everything to work up until adding a socialapp. I have already run migrate and makemigrations and looking at showmigrations, it looks like all have been made. Is there something that I am missing? or do I need to go into my DB and create the table manually? -
Bootstrap modal problem in Django project
Im trying to use a bootstrap modal as part of my web application, but the pop up wont show when the button is pressed. I have copied all the code exactly as it is on the bootstrap site. <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> Any help will be appreciated! I tried copying the code directly as it is from the bootstrap website but no joy. -
limit resources for authenticated user in flask or Django
Currently im planning to distribute resources such as memory, cpu and other resources based on the authenticated user. I tried to search on how can i implement it but i only managed to find rate limit for request and ability to gain information of memory and cpu using psutil. -
How to filter two different columns values together in filter query Django?
I have two columns, For single amount value amount and for range amount values amount_min and amount_max amount amount_min amount_max 25000 0 0 0 100000 300000 Using the following queries, Why it's not showing any of the records ? Jobs.objects.filter(amount_min__gte = 100000, amount_min__lte = 100000, amount_max__gte = 300000, amount_max__lte = 300000,amount__range=(100000, 300000)) and Jobs.objects.filter(amount_min__gte = 10000, amount_min__lte = 10000, amount_max__gte = 50000, amount_max__lte = 50000,amount__range=(10000, 50000)) Can anyone please help me in this query ? -
How can I make themes inside my Django app which can be deployed as well?
What I want is to add a multiple sets of images(themes) and they randomly get allotted to a decision (which is a model in my app) as soon as I create one. I want to display the allotted image on the decision.html, it will always have the same image from then. I want to assign 2 colors and 1 image in each image_set(theme) and while the creation of decision, the decision randomly gets one image_set. It is like changing the color of some of the buttons on the decision.html based on the image that has been allocated to the decision which is currently being seen. And I myself will assign the images and colors of an image_set(not a CRUD setup for any user to upload), somewhere like what color which button will receive associated with the image. It is not that a user will upload images. I want to assign somewhere that image_set_1 has this image, and has 2 colors assigned with every image_set. Then to get image and color from the image_set, and the image_set will get the image from some folder and the same set of images to work in the deployed version as well. please suggest me … -
Django 'NoneType' object has no attribute '_prefetch_related_lookups' disappears after reboot
I am having an intermittent issue with my Django web app where the error above appears every few days on one of my forms. Restarting the webserver resolves the issue and I am at a loss of what is going on. I have other views with similar code that don't have the same problem. I am using django.db.backends.sqlite3 as the database. The form basically collects a bunch of data and on submission goes to another page to generate a PDF using the values entered. It's failing trying to bring up the form. views.py def generate_correspondence_form(request, file_id): file = File.objects.get(id=file_id) if request.method == 'POST': placeholderform = CorrespondencePlaceholderForm(request.POST) correspondenceform = GenerateCorrespondenceForm(request.POST) if correspondenceform.is_valid() and placeholderform.is_valid(): request.session['a'] = list(placeholderform.cleaned_data.get('a').values('id')) request.session['b'] = list(correspondenceform.cleaned_data.get('b').values('id')) request.session['c'] = correspondenceform.cleaned_data.get('c') request.session['d'] = correspondenceform.cleaned_data.get('d').id request.session['e'] = correspondenceform.cleaned_data.get('e') request.session['f'] = correspondenceform.cleaned_data.get('f') request.session['g'] = correspondenceform.cleaned_data.get('g') request.session['h'] = correspondenceform.cleaned_data.get('h') request.session['i'] = correspondenceform.cleaned_data.get('i') if correspondenceform.cleaned_data.get('j'): request.session['j'] = correspondenceform.cleaned_data.get('j').id if request.POST.get('submit_ashtml'): url = f"{reverse('logs:generate_correspondence', kwargs={'file_id': file_id})}?as=html" return redirect(url) else: return redirect('logs:generate_correspondence', file_id=file_id) else: placeholderform = CorrespondencePlaceholderForm() correspondenceform = GenerateCorrespondenceForm() placeholderform.fields['a'].queryset = A.objects.filter(target__file=file) correspondenceform.fields['b'].queryset = B.objects.filter(file=file) context = {'correspondenceform': correspondenceform, 'placeholderform': placeholderform, 'file': file} return render(request, 'logs/generatecorrespondenceform.html', context) -
Question from a total beginner, how do i run a django project on my browser using windows operating system?
I have trouble running a django project on my browser using windows operating system. I tried running the command "py -m manage runserver" on the terminal but instead this happens; Screenshot of the window -
No matching distribution found for django on Window 11
I am new to windows, have been a Macbook user for years. I need to setup an existing project on Windows 11. I have installed python, pip, pipenv and pyenv. I have activated a shell to run the following command: pipenv install --dev Result ERROR: No matching distribution found for django Seems pipenv can not find any of the distributions at all. Not just Django. How can I resolve this? -
Verify token coming from frontend in DJANGO using AUTH0
from django.contrib.auth.backends import BaseBackend from accounts.models import User from urllib.request import urlopen import json from authlib.jose import jwt from authlib.jose.errors import JoseError from authlib.oauth2.rfc7523 import JWTBearerTokenValidator from authlib.jose.rfc7517.jwk import JsonWebKey from authlib.oauth2.rfc6750 import BearerToken class Auth0JWTBearerTokenValidator(JWTBearerTokenValidator): def __init__(self, domain, audience): issuer = f"https://{domain}/" jsonurl = urlopen(f"{issuer}.well-known/jwks.json") public_key = JsonWebKey.import_key_set( json.loads(jsonurl.read()) ) super(Auth0JWTBearerTokenValidator, self).__init__( public_key ) self.claims_options = { "exp": {"essential": True}, "aud": {"essential": True, "value": audience}, "iss": {"essential": True, "value": issuer}, } def validate_token(self, token, scopes, request): # Overriding the validate_token method claims = super().validate_jwt(token) return claims class Auth0AuthenticationBackend(BaseBackend): def authenticate(self, request, token): domain = "domain" audience = "audience" validator = Auth0JWTBearerTokenValidator(domain, audience) try: # token_obj = BearerToken(token, None) claims = validator.validate_token(token, [], request) auth_id = claims["sub"] except JoseError: return None try: user = User.objects.get(auth_id=auth_id) except User.DoesNotExist: user = User.objects.create( auth_id=auth_id, name=claims["name"], email=claims["email"] ) return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None So this is my authentication.py code in which I am creating a user in the backend to allow other models to be tied with the user. And I am trying to set up auth0 such that it receives the token from the frontend, and I have the permissionClasses =[isAuthenticated] on my views so it … -
Filter through 3 nested forloops in django
I am trying to filter through 3 nested forloops and having 2 problems. My first problem is that I cannot find a way to only show child loop objects in relations to parents loop object id. In my example below, I want to show all the B objects (child) for each A objects (parent). My second problem is that I want to filter the last loop and only show the latest child object in each parent category. I have seen a few solution on this forum calling set.all but no success for me. I think my problem here is that there is no direct relation between the model in loop 2 and 3, and I am not sure how to address the "indirect relation". Essentially I am trying the render the following: without filters | C| A| B| |:---- |:------:| -----:| | objectC1| objectA1| objectB1| |objectC1 | objectA1| objectB2|| |objectC1 | objectA2| objectB3|| with filters | C| A| B| |:---- |:------:| -----:| | objectC1| objectA1| objectB1| | | Two | objectA2|objectB3| class A(models.Model, HitCountMixin): name = models.CharField(verbose_name="Name",max_length=100, blank=True) class B(models.Model): user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE) venue = models.ForeignKey(A, blank=True, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) class C(models.Model): title … -
Bootstrap’s cards. How to make fixed card size with many words in it. Django & CSS
I am using the Bootstrap's card to display my journals. It looks like this: Journal List However, when I insert a lot of word, the card size will be veryyyy long. Journal List With really long essay How to make it when there are long essays, it will shown like this: Today is a good day. I started my day with coding. However, I found out that I ... Make it like "..." This is the html code: <div class = "container mt-4 mb-4"> <div class="center_journal"> <div class="col"> <div class="row"> {% for journal in journals %} <div class="card d-flex flex-column col-4 " style="width: 36rem;"> <h5 class="card-title text-center mt-4"><a href="{% url 'journal_detail' journal.id %}" >{{ journal.title }}</a></h5> {% if journal.photo %} <img src="{{ journal.photo.url }}" class="card-img-top" alt="..."> {% endif %} <div class="card-body"> {% if journal.audio %} <audio controls> <source src="{{ journal.audio.url }}" type="audio/ogg"> <source src="{{ journal.audio.url }}" type="audio/mpeg"> <source src="{{ journal.audio.url }}" type="audio/wav"> Your browser does not support the audio element. </audio> {% endif %} <p class="card-content text-center">{{ journal.content }}</p> <p class="text-center font-weight-light">Created on {{ journal.date_created|date:'Y-m-d H:i' }}</p> {% if journal.favourite %} <div class="text-center font-weight-light"> <p>Added to Favourite!</p> </div> {% endif%} <!-- <div class="text-center"> <a href="{% url 'journal_detail' journal.id %}" ><button … -
Django save data accross several signals: m2m_changed
I need testers and engineers to be notified when they're added to a given a model like this: Class Foo(models.Model): engineer = models.ManyToManyField(User, related_name='foo_engineer') tester = models.ManyToManyField(User, related_name='foo_tester') ... Note that it's possible that a User could be both a tester and an engineer. So I have this: def personell_change(sender, **kwargs): if kwargs.get('action') == 'post_add': added = kwargs.get('pk_set') notify_added() m2m_changed.connect(personell_change, sender=Foo.engineer.through) m2m_changed.connect(personell_change, sender=Foo.tester.through) This works, but if the tester and the engineer were the same User, then notify_added() is run twice, which is not ideal. So the question: Is there any way to store the results of the signals until all of them have run? I suppose I could use a pre_save signal to build something to hold the values, and a post_save signal to act on them, but that seems like a bad idea. -
Can we create database, add configuration in settings file in Django testcase and after testcase run, drop database and remove configurations?
Actually, I have an API endpoint in Django, in which I am running a script that creates database on runtime and add configurations in settings file. When I wrote testcase for that endpoint, It throws the following error while tearing down the testcase. ERROR: tearDownClass (tenants.tests.test_apis.test_tenant_apis.TenantCreationTests) Traceback (most recent call last): File "/home/dev/Documents/MUSEAPI/muse-api/venv/lib/python3.8/site-packages/django/test/testcases.py", line 372, in _remove_databases_failures setattr(connection, name, method.wrapped) AttributeError: 'function' object has no attribute 'wrapped' Below is the script, I am using for database configuration import json import environ import psycopg2 from django.conf import settings from django.core.management import call_command env = environ.Env( DEBUG=(bool, False) ) environ.Env.read_env() def configure_db_script(db_name): db_configuration = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': db_name, 'USER': env('DATABASE_USER'), 'PASSWORD': env('DATABASE_PASSWORD'), 'HOST': env('DATABASE_HOST'), 'PORT': env('DATABASE_PORT'), } db_configuration1 = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': db_name, 'USER': env('DATABASE_USER'), 'PASSWORD': env('DATABASE_PASSWORD'), 'HOST': env('DATABASE_HOST'), 'PORT': env('DATABASE_PORT'), 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'CONN_HEALTH_CHECKS': False, 'OPTIONS': {}, 'TIME_ZONE': None, 'TEST': { 'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None } } default_connection = psycopg2.connect( database='postgres', user=env('DATABASE_USER'), password=env('DATABASE_PASSWORD'), host=env('DATABASE_HOST'), port=env('DATABASE_PORT'), ) settings.DATABASES[db_name] = db_configuration1 with default_connection.cursor() as cursor: default_connection.autocommit = True cursor.execute(f'CREATE DATABASE {db_name}') with open('settings.py', 'r') as f: data = f.readlines() with open('settings.py', 'w') as f: for line in data: if line.startswith('DATABASES'): db_json = … -
Issue with @login_required function in Django
I'm receiving an error when trying to use the login_required function. I'm receiving a TemplateDoesNotExist at /accounts/login/ registration/login.html Error. While I have no directory Registration, I have my templates in a folder, templates. I have a login.html template which works fine for the login page. This is the view`I'm using the login_required function on @login_required(login_url='signin') def buy_crypto(request): if request.method == 'POST': currency = request.POST.get('currency') amount = Decimal(request.POST.get('amount')) price_per_unit = Decimal(request.POST.get('price_per_unit')) purchase = CryptoPurchase(user=request.user, currency=currency, amount=amount, price_per_unit=price_per_unit) purchase.save() return redirect('index') else: return render(request, 'buy_crypto.html') My url patterns for User Authentication are in a seperate app in the same project. This app is called accounts. Here's the accounts/urls.py file from django.urls import path from cryptoapp import views from .views import signupView, signinView, signoutView urlpatterns = [ path('create/', signupView, name='signup'), path('login/', signinView, name='signin'), path('signout/', signoutView, name='signout'), ] If you need any further code please let me know ! Any help would be greatly appreciated ! -
best realtime Web framework
Which backend framework is best suited for sending location data from mobile app to website in realtime. I am a beginner in web development and trying to build a real time system, I was told that django is good for learning curve , but node js is good for realtime system, please help me in suggesting the correct framework, -
Django QR code send inline via email is not showing in body
I am trying to send a QR Code to email and have it display inline within the email body. The email is sent successfully, The attachment currently works and displays as expected but the png within the body is showing as a ? and looks like this: In my view I have the following function defined. def send_qr_code_email(to_email, qr_code_data): # Generate QR code image qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(qr_code_data) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") # Convert image to bytes and attach it to the email message buffer = BytesIO() img.save(buffer, 'PNG') image_data = buffer.getvalue() image_filename = 'qr_code.png' data_uri = 'data:image/png;base64,' + base64.b64encode(buffer.getvalue()).decode('ascii') src = 'data:image/png;base64,{0}'.format(data_uri) email = EmailMessage( 'QR Code', render_to_string('Templates/email.html', {'qr_code_data': qr_code_data, 'src': src}), settings.DEFAULT_FROM_EMAIL, [to_email], reply_to=[settings.DEFAULT_FROM_EMAIL], ) email.content_subtype = "html" email.attach(image_filename, image_data, 'image/png') # Send the email email.send(fail_silently=False) and this is my email.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>QR Code</title> <style> .qr-code-container { display: inline-block; border: 1px solid #ccc; padding: 10px; background-color: #fff; box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1); } .qr-code-container img { display: block; margin: 0 auto; max-width: 100%; } .qr-code-container p { margin: 10px 0; font-size: 14px; line-height: 1.5; } </style> </head> <body> <div class="qr-code-container"> <p>Here is your QR code:</p> …