Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nginx not seeing static files, when launching with docker compose +gunicorn
The thing is that i have set up dockerfiles, docker-compose is running everything as it should be. Databases is connected and all the staff. But the only problem is, that i cant load staticfiles. Gunicorn informs, that files "Not Found" both admin, and rest_framework static files. When im doing "docker-compose up" it says that `0 static files were copied to '/static', 165 unmodified So far i have checked paths which are configured in STATIC_ROOT and STATIC URL. Also, modified my docker-compose file: version: '3.11' services: django_gunicorn: volumes: - static:/static/ env_file: - .env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static/ ports: - "80:80" depends_on: - django_gunicorn - db db: image: postgres expose: - 5432 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres volumes: static: Also i have inspected nginx config file one more time: upstream django { server django_gunicorn:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { autoindex on; alias /static/; } } i have also tried different approaches to setting up root and url of staticfiles, but left it like this for now: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' Also there were suggestions to run "collectstatic" first, which i … -
Duplicated reponse with axios in React component's lifecycle method
everyone I'm making a web app and configured a Django backend server to which I make API calls with axios.get. The problem is, the middleware code is being executed twice and I don't understand why, I'm using the API call within a React component's lifecycle method: componentDidMount() { console.log('This line prints only once in the console'); axios.get("http://server:port"). .then((response) => { console.log('This line prints twice in the console!'); }) .catch((err) => console.log(err);); } I was expecting the second call (in the dummy code snippet) to be executed only once... Am I doing something wrong? Can somebody explain what is going on? Thank you in advance for your attention. -
ForeignKey with multiple dependencies
Assume there are some number of buildings located in several locations (BL). Each building can have a certain building type (BT), for example it can be a residential house, a hospital or a school. The choice of construction material (CM) used to build buildings' walls depends on BL and BT. How can I declare CM in my models, so that my app determines CM based on the selection of BL and BT? I assume regular ForeignKey won't work in this case. -
Django: Unable to Apply Function View Decorator to Class Based View
I'm migrating from regular function based views, to class based views. One of the things that I couldn't migrate were the decorators I used. The decorator in question checks if the credentials of the current user are valid and then executes the decorated function: def custom_auth(function): @wraps(function) def wrap(request, *args, **kwargs): # Logic for validating if user has correct credentials # Fetches the user that accessed the function user_object = User.objects.get(username=request_username) # Try to execute the decorated function. If it fails, redirect # to previous page and show an error popup try: return function(request, user=user_object, *args, **kwargs) except: # Logic for displaying the popup Previously I could just decorate my function by doing @custom_auth def view(request, *args, **kwargs): # View logic However, when I try to apply it to my class based view in the same way, I get an error saying __init__() takes 1 positional argument but 2 were given: @custom_auth class CBV(View): def get(self, request, *args, **kwargs): # Get request logic I know that this is not the way you are supposed to apply the decorator, so I tried with different approaches. Either adding the decorator to urls.py, adding the @method_decorator(custom_auth, name="dispatch") or simply overriding the dispatch method, … -
How do I filter data in a ForeignKey Django to display the corresponding data?
class Entrepreneur(models.Model) f ... Class Skills(models.Model) usevalue = models.ForeignKey(Entrepreneur) rating = (rating = models.PositiveSmallIntegerField(validators=[MinValueValidator(0),MaxValueValidator(5)]) Hello I am on a professional project and I had a question given that I am a young developer for the moment I did not know how to filter the data of the skills model for the entrepreneur and that I can filter it and then I can display it on the frontend. Thank you for your answers. -
How do I use allauth with out unexpectedly closed
I was trying to add ALLAUTH to my django app Settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "xxxxxx@gmail.com" EMAIL_HOST_PASSWORD = "xxxxxxxx" urls.py path("accounts/user/<pk>", views.OtherProfileView.as_view(), name='profile_view'), path("password/change/", PasswordChangeView.as_view( template_name='accounts/password_change.html', success_url="/", form_class=PasswordChangeForm), name='password_change'), path("passoword/reset/", views.CustomPasswordReset.as_view(), name='password_reset'), path("password/reset/confirm/<uidb64>/<token>/", PasswordResetConfirmView.as_view( template_name='accounts/password_reset_confirm.html'), name='password_reset_confirm') I expected email will recieve me email reset to my mai` -
Django ForaignKey attribute not showing up in html
So, i have some models and connected each other. And in my views i get chapter model ordered by date published, then remove the ones with same manga(foraign key associated with other model). But apperantly accept for the fields not connected with anything i can't acces the models fields. But also because i am working with a quaryset i cant sort by id or anything, also have to acces the manga models fields associated with chapter. but it does not show up in html. how can i do it ? my models : class Manga(models.Model): manga_name = models.CharField(max_length= 255, default="null") manga_image = models.ImageField(upload_to="thumbnail", default="thumbnail/noimage.png") manga_views=models.IntegerField(default=0) def __str__(self): return f"{self.id}, {self.manga_name}" class Fansub(models.Model): fansub_name = models.CharField(max_length=255, default="null") def __str__(self): return f"{self.id}, {self.fansub_name}" class Chapter(models.Model): chapter_number = models.IntegerField(default=0) chapter_url = models.URLField(default="www.example.com") manga = models.ForeignKey(Manga, on_delete=models.CASCADE) fansub = models.ForeignKey(Fansub, on_delete= models.CASCADE) relase_date= models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.chapter_number}, {self.manga}, {self.fansub}" my view : def Index(request): manga = Manga.objects.all() chapter = Chapter.objects.all().values() fansub = Fansub.objects.all().values() mostview = manga.order_by("-manga_views")[:5] relasedateorder = chapter.order_by("relase_date") context= { "Manga": manga, "Chapter": chapter, "Fansub": fansub, "Mostview": mostview, "LastUpdated": relasedateorder, } template = loader.get_template("Index.html") and finnaly the html: {%for d in LastUpdated%} <p>{{d.manga}}</p> {%endfor%} -
Prevent duplicated scans in a single QR code scan in DJango
The current camera scans the QR code and posts the same value to view_nurse.py multiple times till the QR code is moved away from the camera. This causes my database to have many repeated values shown in the image below. How do I prevent this from happening? In situations where I scan another QR code without relaunching the camera, the program should be able to detect that it is a new QR code and POST the results into the views_nurse.py. <nurse_home.html> {% load static %} {% block mainbody %} <title>Django Online Barcode Reader</title> <meta charset="utf-8"> {% csrf_token %} <script src={% static "js/html5-qrcode.min.js" %}></script> <style> .result{ background-color: green; color:#fff; padding:20px; } .row{ display:flex; } </style> <!--<form action="" method="POST">--> {% csrf_token %} <div class="row"> <div class="col"> <div style="width:500px;" id="reader"></div> </div> <div class="col" style="padding:30px;"> <h4>Scanned Result</h4> <!--<div id="result" name="result">Result Here</div>--> <output type="POST" id="result" name="result" placeholder="qrCodeMessage"> {% csrf_token %} </div> </div> <script type="text/javascript"> // 1) Create a function to get the CSRF token function getCookie(name) { let cookie = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)"); return cookie ? cookie[2] : null; } // 2) After generating the qrcode in the onScanSuccess callback, you invoke sendQrCode function with the qr code as argument function onScanSuccess(qrCodeMessage) … -
form post request not sending data to django views.py. please help me
i am passing data from edisplay.html to views.py class name called EmailManagement but after inserting data data goes blank even i type it and i fell auto submitted when i type first form because myform appear only first form validation. views.py @csrf_exempt def EmailManagement(request): if request.method == "POST": code = request.POST.get('scode_no', '') if code: userlogin = EmailDb.objects.all().filter(scode = code) scode = '' for i in userlogin: scode += i.scode # print(scode) if code == scode: sem = EmailDb.objects.all().filter(scode = code) idv = '' for i in sem: idv += str(i.id) print(idv) idv = int(idv) p = EmailDb.objects.get(id=idv) if request.method == 'POST': institution = request.POST.get('institutionf', '') fullname = request.POST.get('fullnamef', '') email = request.POST.get('personalef', '') contact = request.POST.get('contactf', '') position = request.POST.get('positionf', '') uploaded = request.FILES.get('filef', '') print(uploaded) print(fullname) p.institution = institution p.fullname = fullname p.contact = contact p.email = email p.position = position p.uploaddata = uploaded p.save(update_fields=['institution', 'fullname', 'contact', 'email', 'position', 'uploaddata']) form = pForm() return render(request, 'NEC/edisplay.html', {'p': p, 'form': form}) form = ResultForm() return render(request,'NEC/emailmgt.html', {'form': form}) edisplay.html <form hx-post="email" hx-target="body" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{p.useremail}}here <!-- <input type="text" name="institution" id="institution" placeholder="Institution Name" class="form-control w-50 form-row" value="{{p.institution}}" required> <input type="text" name="fullname" id="fullname" placeholder="Full Name" class="form-control w-50 form-row mt-1" … -
Django DRY need
I call the "dispatch" method in all of my CRUD classes. How can I put it somewhere else to avoid repetition? ideally in an external file Thanks a lot class PublicationsListView(LoginRequiredMixin, TemplateView): template_name = 'pages/publications/index.html' def dispatch(self, request, *args, **kwargs): if (self.request.user.groups.filter(Q (name='proprietaire') | Q (name='super-administrateur')).exists()) and 'flotte_id' not in self.request.session : messages.warning(self.request, mark_safe("Veuiller choisir ...")) return redirect('dashboards:home') else : return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): .... i tried de put the method elsewhere , but each time : "self" or "request" undefined -
How to concating two field with in django queryset?
Hy there, Concating two field raise TypeError: select_format() missing 1 required positional argument: 'params' Here is my model from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation class Report(models.Model): content_type = models.ForeignKey(ContentType, verbose_name=_('content_type'), related_name="content_type_set_for_%(class)s", on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey(ct_field="content_type", fk_field="object_id") and here is my query in views.py from django.db.models import CharField,F,ExpressionWrapper from .models import Report queryset=Report.objects.annotate(combined_field=ExpressionWrapper(F('content_type')+F('object_id), output_field=CharField) queryset.values(combined_field) when i call queryset.values(combined_field) it raise "TypeError: select_format() missing 1 required positional argument: 'params' " Can you guys help me to overcome this problem. Thanks -
Django: html links to the wrong directory for the css
Here is my main page, localhost:8000/helloworld/greeter at helloworld\templates\hello: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Hello!</title> {% load static%} <link rel="stylesheet" type = "text/css" href = "{% static 'hello/site.css' %}" /> </head> <body> <span class="message">Hello there, {{ name }}!</span> It's {{ date | date:'l, d F, Y' }} at {{ date | time:'H:i:s' }}. </body> </html> and here is the CSS file at helloworld\static\hello (so it should look for localhost:8000\helloworld\static\hello\site.css): .message{ font-weight color: blue; } and here is the file structure: The expected behaviour would be that the phrase "Hello there, [name]" is bolded and in blue, but here is what the code actually yields: (this is the problem) And looking within the console gives this error: GET http://localhost:8000/static/hello/site.css net::ERR_ABORTED 404 (Not Found) Notice how it seems to think that "static" is at the root directory, when it is in localhost\helloworld. I would like to find a solution to this problem and change it so that it links to the correct directory I tried to change the block, specifically: <link rel="stylesheet" type = "text/css" href = "{% static 'hello/site.css' %}" /> to: <link rel="stylesheet" type = "text/css" href = "{% 'helloworld/static/hello/site.css' %}" /> I expect that it will apply the site.css … -
How to read CSV file and create User
I want to read and create user from csv file. but my code gave me MultiValueDictKeyError at /api/user/ read and crate user from CSV file my Code is: def read_and_create_csv_file(): header = {'Authorization': f'Token {get_token()}'} url = f"{URL}/api/user/" with open(r"E:\WC_API\employees.csv") as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: data = { "USERNAME": row['username'], "FIRST_NAME": row['FIRST_NAME'], "LAST_NAME": row['LAST_NAME'], "EMAIL": row["EMAIL"], "PASSWORD": "Abc@123"} response = requests.post(url, json=data, headers=header) if response.status_code == 201: print("User created successfully") else: print("Failed to create user") read_and_create_csv_file() this is the resule: Failed to create user or MultiValueDictKeyError -
django migrations file incompatible with windows file naming conventions
The following characters are forbidden in Windows file names: < > : " / \ | ? * In our Git repo, an old migration file "0012_iosversion_iosversion_recommended_>_obsolete.py" is keeping a colleague from cloning the repo. Django auto-generated this file from a model's following: class Meta: constraints = [CheckConstraint( check = Q(recommended__gt=F('obsolete')), name = 'recommended_>_obsolete' )] #12 is not a necessary check we need, however we have 3 newer migrations on top of #12 that create new tables that are currently in use. What is the best practice to rename or remove the file? Can we regenerate all of the migration files in a window safe way Can we rename the file? Rollback all of the changes and drop our tables? -
js doesn't clone button which located inside div
i am writing sell-stuff site and user must have the opportunity to uploads images. Images could be many, that's why using django formset, i've created dynamic form with button that add new file fields for photos. Point is, that i do really need the opportunity to delete images in case i made a mistake and load wrong image. I have js code and html and honestly do not have any idea how i can make my html work properly. PLease help HTML {% for form in formset %} <div class="images_row bird-form" style="margin: 3%"> <label class="input-file"> {{form.image}} <span class="input-file-btn">Выберите файл</span> <span class="input-file-text">Максимум 10мб</span> <button class="DeleteRow btn btn-danger" type="button">Удалить</button> </label> </div> {% endfor %} <button id="add-form" type="button">Добавить изображение</button> </div> </div> Js let birdForm = document.querySelectorAll(".bird-form") let container = document.querySelector("#form-container") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let delBut = document.querySelector(".DeleteRow") let formNum = birdForm.length-1 addButton.addEventListener('click', addForm) function addForm(e){ e.preventDefault() let newForm = birdForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`,'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`) container.insertBefore(newForm, addButton) totalForms.setAttribute('value', `${formNum+1}`) }; -
Django - add a link with custom admin page action - need custom href
I have Django app called my_supper_app with 12 models: ModelA, ModelB, ModelC,...etc. In front end I have views with tables and from those tables I would like to open admin panel (by clicking proper button or link) with corresponging model type and object with corresponding id for edit purpose or delete purpose. How the custom link in frontend should look like? When model is ModelD and id = 9 than my link to admin panel (from broser) look like this: http://127.0.0.1:8000/admin/my_supper_app/modeld/9/change/ How shoud I redirect from front end to admin panel in this case? I have seen sth like: <a href="{% url 'admin:**.....???**' %}" class="btn btn-high btn-success">Edit modelD with ID equal to 9 (in admin panel)</a> -
In django admin module, foreignkey shows xxx_object(xx) instead the real name
I am new to django. I had two model and want to manage them in admin module. The 1st module like this: class Domain(models.Model): id = models.AutoField(primary_key=True) domain = models.CharField(max_length=250, blank=False) deptname = models.ForeignKey(to="Department", to_field="dwmc", on_delete=models.CASCADE, related_name='+',) class Meta: verbose_name = 'Domain' verbose_name_plural = 'Domains' pass The second like this: class Department(models.Model): dwdm = models.CharField(max_length=250, null=False, default='') dwmc = models.CharField(unique=True, max_length=200, blank=True) class Meta: verbose_name = 'Demartment' verbose_name_plural = 'Department' pass While domain is all my domains, and department is all my departmenst. In department model, dwdm is the dapartment id(numbers, such as 001,002...), dwmc is the real department name(such as IT, HR). And in the database, the data is correct. In admin module, I can add/edit the entries, but the deptname show not the real name, it shows like this: enter image description here Well, which step I made the mistake? Thanks a lot. -
needs to have a value for field "id" before this many-to-many relationship can be used / Django
If you create clothes in admin, the above error "<Clothes: None: 0>" needs to have a value for field "id" before this many-to-many relationship can be used.. We also found that this error occurs on the save of the Clothes model. This problem seems to be that the pk value is not assigned, so I tried using primary_key=True, but it doesn't seem to be the case. I have one more question. The likes of the Post model are also the same code as the save of the Clothes model, but the Post model is created without any problems. For what reason? Below is the code of model.py from django.db import models # from django.contrib.auth.models import User from django.conf import settings # from server.apps.user.models import Profile class Clothes(models.Model): CATEGORYS =[ (0, '상의'), #상의 (1, '하의'), #하의 (2, '아우터'), #아우터 (3, '신발'), #신발 (4, '악세사리'), #악세사리 ] category = models.IntegerField(default=0,choices=CATEGORYS) img = models.ImageField(upload_to='main/images/clothes/%Y/%m/%d') save = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Save', blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) buying = models.TextField(null=True, blank=True) def __str__(self): return f'{self.pk}: {self.category}' #pk가 존재하지 않는것 같음. # class SavePeople(models.Model): class Post(models.Model): main_img = models.ImageField(upload_to='main/images/post/%Y/%m/%d') title = models.CharField(max_length=100) content = models.TextField() private = models.BooleanField(default=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) clothes = models.ManyToManyField(Clothes,related_name='Clothes') likes = models.ManyToManyField(settings.AUTH_USER_MODEL, … -
How to hide current image URL class-based view Django
I'm using class-based view and i have problem hiding my current image location in my page. here is my models.py card_image = models.ImageField( upload_to="buildings/main", null=True, verbose_name="Main picture" ) and this is my building.html {% csrf_token %} {% for field in form %} <div class="col-5"> {{ field.label_tag }} </div> <div class="col-5"> {{ field }} </div> {% endfor %} <img width="200vm" src="/media/{{ form.card_image.value }}"/> and this is the image of what I'm trying to hide(https://i.stack.imgur.com/1U4Yx.png) I had some research but all of them were changing the template {{image.url.value}} but I don't want to write anything outside my for loop -
Django ORM TruncDay works incorrectly
I'm trying to get time left till the day of an event using this annotation from django.db.models.functions import Now, TruncDay Events.objects.annotate(time_left=TruncDay("start")-Now()) where "start" is the column holding date and time when the event starts. Then if I print the "time_left" field of a resulting object I get wrong time which is bigger by my time zone shift. How can I fix that? -
AWS cognito required login in django rest api
I'm working on integrating aws congito login/register in a django react js app and i want to add the login_required decorator with cognito . Any kind of information will be appreciated -
Not able to save data from aDjango form: Django 4.1, Windows 10
I am working on a small student application. I designed a table for storing students' information in which those fields of information are requested at the first registration and those can be updated later or updated during the process. For example, a student's information can update in the process by putting on-hold (update the onhold field) in case that student has been absent for 3 weeks. Below is my code. ###Model.py from django.db import models from django.contrib import admin from django.utils.translation import gettext_lazy as _ class Student(models.Model): #std_matricule = models.CharField(verbose_name='Student matricule', max_length=6, null=False, unique=True, primary_key=True) std_matricule = models.CharField(verbose_name='Matricule', max_length=6, null=False, unique=True, blank=False, help_text='Matricule of the student') std_parents = models.ForeignKey(Parents, on_delete=models.DO_NOTHING, related_name='Parents', unique=False, default=1, verbose_name='Student parents') std_email = models.EmailField(verbose_name='Email', null=False, blank=True, help_text='Enter the email of the student or leave blank if not exist') std_password = models.CharField(verbose_name='Password', max_length=64, null=False, blank=True, help_text='Type the password with 6 characters minimum') std_surname = models.CharField(verbose_name='Surname', null=False, blank=False, max_length=64, help_text='Type the Surname of the student as in the birth certificate') std_firstname = models.CharField(verbose_name='First name', null=False, blank=True, max_length=64, help_text='Type the student first name') std_nickname = models.CharField(verbose_name='Student Nickname', max_length=64, null=False, blank=True, help_text='If exist, type student nickname here') class Sex(models.TextChoices): MALE = 'Male', _('Male') FEMALE = 'Female', _('Female') std_sex = models.CharField( … -
Using django-import-export: How to customise which fields to export Excel files
I just starting out using Django. I'm using django-import-export package and I tried to customize my Django admin panel in this page in order to choose which fields to export to excel file. Here is my admin model class CompanyAdmin(ImportExportMixin, admin.ModelAdmin): model = Company resource_classes = [CompanyResource] list_display = [ "name", "uuid", ] fields = [ "name", "email", ] def get_export_resource_kwargs(self, request, *args, **kwargs): formats = self.get_export_formats() form = CompanyExportForm(formats, request.POST or None) form_fields = ("name", "email", ) return {"form_fields": form_fields} Here is my model resource class CompanyResource(resources.ModelResource): class Meta: model = Company def __init__(self, form_fields=None): super().__init__() self.form_fields = form_fields def get_export_fields(self): return [self.fields[f] for f in self.form_fields] Here is my export form class CompanyExportForm(ExportForm): # what should i write here? is this the place that i should write the custom code eg: checkboxes where user have the options to export the 'name` or 'email' fields ?? I try to use the same way as in this post in order to achieve the same result. However, i have been stuck forever. -
Django deploy on AWS EB CLI
I'm trying to deploy a basic Django project on AWS using ElasticBean. I tried everything, but can't understand what mistake I have done. So I will summarise here all 'solutions' on the internet. Please help ! First of, this is my Django project: .ebextensions -django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: ebdjango.settings .elasticbeantalk branch-defaults: default: environment: eb-env global: application_name: ebdjango branch: null default_ec2_keyname: null default_platform: Python 3.8 default_region: us-west-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application settings.py ALLOWED_HOSTS = ['http://ebdjango-env.eba-b3pcnpc8.us-east-1.elasticbeanstalk.com/'] wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ebdjango.settings') application = get_wsgi_application() requirements.txt Django==3.2 gunicorn==20.1.0 There is nothing in my Django app, no templates, no modules. I created it to be able to upload it. I'm using Django 3.2 and Python 3.8 When loading the webpage (CNAME): 502 Bad Gateway / nginx/1.22.1 When looking the log file I see this error: web: ModuleNotFoundError: No module named 'ebdjango.wsgi' The entire project is available here: https://github.com/mkchmura/AWS-EB-CLI.git -
TypeError : expected bytes-like object, not HttpResponse
i am trying to send an email with pdf file attached. But I have an error when sending the email in my project django utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None views.py def sendMail(request): pdf = render_to_pdf('cart/commande.html',context) subject, from_email, to = 'Message with pièce joint : N° 0001', 'aab@gmail.com', 'too@gmail.com' text_content = 'hello' html_content = '<p>hello, .</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.attach('commande_pdf',pdf,'application/pdf') msg.send() return render(request,'cart/succes.html') the error points to this line msg.send Noted the generation of the pdf file is OK, it must be attached to the email