Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Classes in Django views.py - confused
I couldn't find the answer to my question here, which probably means I'm barking up the wrong tree. I have a Django site where I would like to create a page that uses BioPython to retreive the last x records from PubMed for a specific search string. The BioPython output is tricky, so to get the title and abstract I played around and wrote some test code that outputs a dictionary that could be looped over in a Django template. (thanks to Marco Bonzanini https://gist.github.com/bonzanini/5a4c39e4c02502a8451d) from Bio import Entrez from pmterm import term def search(query): Entrez.email = 'david.hallsworth@x.com' handle = Entrez.esearch(db='pubmed', sort='pubdate', retmax='20', retmode='xml', term=query) results = Entrez.read(handle) return results def fetch_details(id_list): ids = ','.join(id_list) Entrez.email = 'david.hallsworth@hotmail.com' handle = Entrez.efetch(db='pubmed', retmode='xml', id=ids) results = Entrez.read(handle) return results title_abstract = {} if __name__ == '__main__': results = search(term) id_list = results['IdList'] papers = fetch_details(id_list) for i, paper in enumerate(papers['PubmedArticle']): title = (paper['MedlineCitation']['Article']['ArticleTitle']) abstract = '' try: for a in paper['MedlineCitation']['Article']['Abstract']['AbstractText']: abstract += (a + " ") except KeyError: abstract = 'No abstract available' title_abstract[title] = abstract However, I now realise that I also want to store the citation and link url, so a dictionary probably isn't the way forward. In β¦ -
How to make DRF serializer compatible with uppercase
My Boss decided to migrate Rest API from Java to Django. The previous Java guy designed every database field in camelCase, such as "userName", and every API POST data in camelCase. When I refactor these to DRF, I got following Model. The REST API also receive post data in camelCase, so I must lower the post data or is_valid() will return False. class Useraccount(models.Model): username = models.CharField(db_column='userName') REST API REQUEST DATA: { "userName": "Jenny" # I need lower "userName" to "username" } Is there a method to let DRF compitable with uppercase POST DATA? I don't want to lower these "userName" in every APIView. -
nginx: How can I remove port from url?
I have a vps server and domain Nginx /etc/nginx/sites-available/myproject and /etc/nginx/sites-enabled/myproject server { listen 80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } /etc/nginx/nginx.conf ... http { ... include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*.*; } nginx -t - successful systemctl status nginx - active ufw status Status: active To Action From -- ------ ---- 8000 ALLOW Anywhere 80 ALLOW Anywhere 443 ALLOW Anywhere 8000 (v6) ALLOW Anywhere (v6) 80 (v6) ALLOW Anywhere (v6) 443 (v6) ALLOW Anywhere (v6) When I open ip of vps-server in browser I get home page of nginx. gunicorn /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=root WorkingDirectory=/home/myproject ExecStart=/home/myproject/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-enabled# cat /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target systemctl status gunicorn - active gunicorn --bind 0.0.0.0:8000 myproject.wsgi - working /run/gunicorn.sock - exists Django /home/myproject/myproject/.settings.py ALLOWED_HOSTS = ['example.com', 'localhost'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test_db', 'USER': 'test_user', 'PASSWORD': 'test', 'HOST': 'localhost', 'PORT': '', } } I'm run a manage.py runserver example.com:8000 and get response from Django, that the server is started on example.com:8000. β¦ -
Integrate legacy database to a new Django app
I developed a new cms using django and wagtail. News website that I developed the CMS for, used to use a php cms storing data in a messy and not normalized mysql database. So now, I have to store all old database records in my new django app's database. As the links to news in old cms were generated based on their ID and obviously the old links should keep pointing to the corresponding content, I have to keep IDs as well as other fields. Right now I am confused about what approach should I take in order to do the job. Basic idea is to use inspectdb generating a new model for records in old database, then write a script to fetch each object from old db, use it to generate an object of newly developed models and save the object in new database. What more efficient approaches can I take? -
How to convert 12 hr date time format to 24 hr format using java script?
I am sending the data from my database as 24 hr format, but when i use it on front-end for time counter as below the output gives 'none'. Also,When I print the 'plan_deactive_date' it shows time in 12 hr format. So, is there any way to convert the datetime from 12 hr format to 24 hr format? ''' <script> // Set the date we're counting down to var countDownDate = new Date("{{plan_deactive_date}}").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date().getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display the result in the element with id="demo" document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m β¦ -
Custom Success Message in django Admin
I am trying to make custom Admin Successful messages but don't know how to do that I have a picture of successful message: https://i.stack.imgur.com/2SVuL.png -
Django Internal Server AWS Elastic-Beanstalk
I have a basic Django project that I am trying to deploy on an AWS Beanstalk instance. The Django project worked perfectly on my local machine but I am at my wits end with trying to get it running on AWS. I have tried multiple tutorials (the official AWS one, the Real Python and others) without success. I feel like im almost there, but after deploying to AWS with no ERRORs i get an "Internal Server Error" when i try the AWS generated URL. I am using the AWSEBCLI package from command prompt to deploy the project. Project was made using an Virtual Environment and im using a PC with Windows 10. Django Folder Structure (project name is wt): wt |.gitignore |db.sqlite3 |manage.py |Pipfile |requirements.txt β+βββ.ebextensions βββ|django.config βββ|01_packages.config β+βββ.elasticbeanstalk β+βββpages β+βββtemp β+βββwt βββ|settings.py βββ|urls.py βββ|wsgi.py βββ|__init__.py Before uploading, the project was git commit'd and python manage.py collectstatic'd and after the application and environment were created in AWS EB i added the AWS URL to the ALLOWED_HOSTS section of settings.py. requirements.txt: `Django==2.2.2 Pillow==6.2.0 psycopg2==2.8.4 pytz==2019.1 sqlparse==0.3.0` django.config: `option_settings: aws:elasticbeanstalk:container:python: WSGIPath: wt/wsgi.py` 01_packages.config: `packages: yum: git: [] postgresql93-devel: [] libjpeg-turbo-devel: []` I have uploaded the eb logs file here: https://gofile.io/?c=KMat86 Im really β¦ -
Explanation for def update(self,instance,validated_data) in Django?
I am a fresher.I don't understand def update function Can any one explain def update function parameters in detail? Thanks in advance :) -
Ban enter to proceed with next question in Django survey
I am writing a short survey in Django. The last question sould be a Feedback form field in which participants can enter their thoughts. However, if I press enter while filling in the feedback, they proceed to the next question. I want to ban the proceeding with enter (just in case they want to write a lot). pages view: class Feedback(Page): form_model = 'player' form_fields = ['feedback'] models view: feedback = models.StringField( label='Is there any Feedback you would like to share?') -
Django OperationalError app cannot connect to Cloud App SQL
I have deployed my Django app to Google Cloud. It worked fine when I hosted it locally and throughout the steps outlined in this post. This is the full traceback. (Torque is the name of my project), and showroom is my app. OperationalError at /showroom/ (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") Request Method: GET Request URL: https://torque-256805.appspot.com/showroom/ Django Version: 2.2.5 Exception Type: OperationalError Exception Value: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") Exception Location: /env/lib/python3.7/site-packages/MySQLdb/connections.py in __init__, line 166 Python Executable: /env/bin/python3.7 Python Version: 3.7.4 Python Path: ['/srv', '/env/bin', '/opt/python3.7/lib/python37.zip', '/opt/python3.7/lib/python3.7', '/opt/python3.7/lib/python3.7/lib-dynload', '/env/lib/python3.7/site-packages'] Server time: Thu, 24 Oct 2019 09:45:29 +0300 ... /env/lib/python3.7/site-packages/MySQLdb/__init__.py in Connect return Connection(*args, **kwargs) β¦ βΆ Local vars /env/lib/python3.7/site-packages/MySQLdb/connections.py in __init__ super(Connection, self).__init__(*args, **kwargs2) β¦ βΆ Local vars ... num_manufacturers = Manufacturer.objects.all().count() β¦ βΆ Local vars The traceback refers to a views attribute. I never had this line of code when hosting it locally. -
its possible to use django mysql modal array filed
In my case i need design my modal in array of fields expected {field 1: string, field 2: [""], field 3: [""] } so far i designed my modal like following: class Collaborator(models.Model): name = models.CharField(max_length=50, blank=True, null = True, ) class Responsibility(models.Model): name = models.CharField(max_length=50, blank=True, null = True, ) class Class1(models.Model): field 1 = models.CharField(max_length=50, blank=True, null = True, ) field 2 = models.ManyToManyField(Responsibility, related_name='res_cards', blank=True,null=True ) field 3 = models.ManyToManyField(Collaborator, related_name='col_cards', blank=True, null=True ) so i am expecting for to get all fields in an array rather than define new modal -
How to change the background color of the top menu dynamically?
I am developing the website on python(Django). I am getting some difficulties to change the background color of the top menu on every page. What I am doing is, I have an index.html page and templates which are aboutus, contactus and service. When I am on the home page then I am getting the gray background of the menu which is correct. Now I am on aboutus and I have to change the menu color from gray to black but I am getting the only gray. So I want to know how do I change the class or override the CSS? Should I need to add the class to the body and then override the menu BG? How do I added the class to the body on each page dynamically? index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title%}Home{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'css/style.css'%}" type="text/css"> </head> <body> <div class="Wrpper"> <header class="bg_gray"><!--top menu code--></header> {% block content %} <!-- template code --> {% endblock %} <footer><!--footer code--></footer> </div> <script src="{% static 'js/jquery.min.js' %}"></script> <script src="{% static 'js/main.js' %}"></script> </body> </html> style.css .bg_gray{background-color: #ccc;} .bg_black{background-color: #000;} aboutus.html β¦ -
Request method mapping is happening after permission check
So, this issue(may not be as issue and error from my side) is something that i faced while testing of my class based views. I had a view that creates and updates user as shown below. class UserViewSet(ViewSet): def check_permissions(self, request): print("Action = ", self.action) if self.action == 'create_user': return True return super().check_permissions(request) def create_user(self, request): # user creation code def update(self, request): #user update code And create_user was mapped with POST method and update was mapped with PUT method. So, my need was that for create_user action no permission is required and for update, user should be authenticated. Overriding check_permssion did the job. Now, when i was testing the create_user end point. I wrote a test that tries to create user using some method other than POST. I expected that the response should be HTTP_405_METHOD_NOT_ALLOWED. def test_create_user_with_invalid_method(self): data = self.user_data response = self.client.put(self.url, data) self.assertEqual(response.status_code, HTTP_405_METHOD_NOT_ALLOWED) But the response was HTTP_401_UNAUTHORIZED. And the action variable was set as None. My url mapping is like this: url(r'^account/register/$', UserViewSet.as_view({"post": "create_user"}),name="account_register_view"), url(r'^account/update/$', UserViewSet.as_view({"put": "update"}), name="account_update_vew"), So looking at this, i thought djago is either doing the mapping of request(method, url) to action either after checking permission or doing it before but setting β¦ -
Converting relative url path to absoliute url for xhtml2pdf
I am very inexperienced in this so I have problem understanding documentation provided for xhtml2pdf since it is very vague in details. Please tell me what I am doing wrong. According to documentation to convert relative url path to absolute I need to use provided function: def link_callback(uri, rel): """ Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources """ # use short variable names sUrl = settings.STATIC_URL # Typically /static/ sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/ mUrl = settings.MEDIA_URL # Typically /static/media/ mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/ # convert URIs to absolute system paths if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) else: return uri # handle absolute uri (ie: http://some.tld/foo.png) # make sure that file exists if not os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl) ) return path I added exact same function to my views.py and using this function for generating pdf (also in views.py, almost directly taken form docs): def PGP_result(request): data = request.session['form_data'] lietuvosPgp = data['LtPGP'] valstybe = data['pVal'] kastai = data['iKastai'] rezultatas = data['result'] today = timezone.now() params = { 'LtPgp': lietuvosPgp, 'Valstybe': valstybe, 'Kastai': kastai, β¦ -
Deploying django project on digital ocean with apache and mod_wsgi
Deploying django project on DigitalOcean with apache and mod_wsgi I'm using Ubuntu 16.04 apache 2.4 python3.5.2 django==1.11 Firebase Installed Apache : https://www.digitalocean.com/community/tutorials/how-to-install-the-apache-web-server-on-ubuntu-16-04 sudo apt-get install build-essential libssl-dev libffi-dev python3-dev sudo apt-get install libapache2-mod-wsgi-py3 sudo apt-get install aptitude sudo aptitude install apache-dev pip3 install mod-wsgi Installed all pip3 modules And apache is running gave permission to www folder as sudo chown -R www-data:www-data www/ My wsgi.py file as import os import sys sys.path.append('/var/www/myproject') sys.path.append('/usr/local/lib/python3.5/dist-packages') os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings" #os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") #also tried from django.core.wsgi import get_wsgi_application application = get_wsgi_application() apache config file 000-default.conf <VirtualHost *:80> ServerName www.mysite.in ServerAlias mysite.in ServerAdmin myemail@abc.com DocumentRoot /var/www/ ErrorLog ${APACHE_LOG_DIR}/mysite_error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite.in python-path=/var/www/myproject python-home=/usr/local/lib/python3.5/dist-packages WSGIProcessGroup mysite.in WSGIScriptAlias / /var/www/myproject/myproject/wsgi.py </VirtualHost> Ran command after modifying 000-default.conf file sudo service apache2 reload sudo a2ensite 000-default.conf sudo service apache2 reload sudo systemctl restart apache2.service My project folder structure is . βββ __pycache__ β βββ config.cpython-35.pyc βββ myproject β βββ __init__.py β βββ __pycache__ β β βββ __init__.cpython-35.pyc β β βββ settings.cpython-35.pyc β βββ settings.py β βββ urls.py β βββ wsgi.py βββ myprojectapp β βββ admin.py β βββ __init__.py β βββ mail_html.py β βββ migrations β β βββ __init__.py β¦ -
Issue for mysql python on installing
I am trying to run a python django project as required version of 2.7 of python , django of 1.8 and mysql 5.7, so while installing the MySQL-python of 1.2.5, buidling the wheel its breaking and getting the below error Building wheel for MySQL-python (setup.py) ... error ERROR: Command errored out with exit status 1: error: command 'cc' failed with exit status 1 i link the mysql@5.7, so when i check which mysql_config i am getting /usr/local/opt/mysql@5.7/bin/mysql_config. i have tried most of the solutions, i have installed mysql through brew. tried installing mysqlclient in virutal env before django gets installed , but when i tried installing mysqlclient in venv i am getting the same error Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: error: command 'cc' failed with exit status 1 i am not able to figure whats the issue, and i am new to python. any help will be appreciated. -
Not able to establish self join in Django App
//I want to dislay name of the sponsors which are also customers. We can under stand this from the data model. In the view page i want to show name of the sponors but i am not able to establish the join between sponsor and its name. Model.py ----------- class customer(models.Model): company = models.CharField(max_length=3) mobile = models.CharField(max_length=10) name = models.CharField(max_length=100) sponsor = models.CharField(max_length=10) # Sponsor is also a customer like employee and manager address1 = models.CharField(max_length=200) country = models.CharField(max_length=101) state = models.CharField(max_length=100) city = models.CharField(max_length=100) zip = models.CharField(max_length=6) email = models.EmailField(max_length=100) status = models.CharField(max_length=1) creator = models.CharField(max_length=20) cretime = models.DateTimeField(default=datetime.now) updator = models.CharField(max_length=20) updtime = models.DateTimeField(default=datetime.now, blank = True ) views.py -------- from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect import datetime from .models import customer from django.db import transaction from django.contrib import messages import re def customer_view(request): name1 = str(request.GET.get('nam')) mobile1 = str(request.GET.get('mob')) if (name1 == 'None' and mobile1 == 'None'): customers_list = customer.objects.all().order_by('-cretime') elif (name1 == '' and mobile1 == ''): customers_list = customer.objects.all().order_by('-cretime') elif (name1 != '' and mobile1 == ''): customers_list = customer.objects.filter(name=name1).order_by('-cretime') elif (name1 == '' and mobile1 != ''): customers_list = customer.objects.filter(mobile=mobile1).order_by('-cretime') else: customers_list = customer.objects.filter(mobile=mobile1) & customer.objects.filter(name=name1).order_by('-cretime') sponsors = customer.objects.all().distinct('mobile') ctx β¦ -
Production ready Python apps on Kubernetes
I have been deploying apps to kubernetes from last 2 years. And in my org all our apps(especially stateless) are running in kubernetes. I still have a fundamental question, just because very recently we found some issues with respect to our few python apps. Initially when we deployed, our python apps(Written in Flask and Django), we ran it using python app.py. Its known that, because of GIL, python really doesn't have support for system threads, and it will only can serve one request at a time, but in case the one request is CPU heavy, it will not be able to process further requests. This is causing sometimes the health API to not work. We have observed that, at this moment, if there is a single request which is not IO and doing some operation, will hold the CPU and cannot really process another request in parallel. And since its only doing less operations, we have observed there are no increase in the CPU utilization also. This has an impact on how HorizontalPodAutoscaler works, its unable to scale the pods. Because of this we started using uWSGI in our pods. So basically uWSGI can run multiple pods under the hood β¦ -
django auto check if i save it to database
here is my html <input type="checkbox" value="1" name="Visual" id="visual"> <input type="checkbox" value="1" name="Tuberculosis" id="Tuberculosis"> <input type="checkbox" value="1" name="Skin" id="Skin"> <script type="text/javascript"> $('#checkbox-value').text($('#checkbox1').val()); $("#checkbox1").on('change', function() { if ($(this).is(':checked')) { $(this).attr('value', 'true'); } else { $(this).attr('value', 'false'); } $('#checkbox-value').text($('#checkbox1').val()); }); </script> this is my views Visual= request.POST['Visual'] Tuberculosis= request.POST['Tuberculosis'] Skin= request.POST['Skin'] V_insert_data = StudentUserMedicalRecord( Visual=Visual, Tuberculosis=Tuberculosis,Skin=Skin ) V_insert_data.save() why is it everytime i save the data on my database, the visual,Tuberculosis,Skin are automatically checked eventhough i didnt check it when i was saving it. or i think my javascript is wrong? -
Not able to save custom profile data on to django model
I have a custom userprofile model and edit profile form. But when I try to save the data into the Profile model using edit profile form. it is not saving into the Profile model. But, as I'm using Django user model, it is saving first_name, last_name, email into the Django user model after saving from EditProfile view I have already created a view function to save the data models.py class Profile(models.Model): user_name = models.ForeignKey(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=100, verbose_name='first_name',blank=True,null=True) last_name = models.CharField(max_length=100,blank=True, null=True) email = models.EmailField(blank=True, null=True, default='name@name.com') date_of_birth = models.DateTimeField(auto_now=False) phone_number = PhoneField(blank=True, help_text='Contact phone number') def __str__(self): return '{} {} {} {} {} {}'.format(self.user_name,self.first_name, self.last_name, self.email, self.date_of_birth, self.phone_number) forms.py class DateInput(forms.DateInput): input_type = 'date' class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'first_name', 'last_name', 'email', 'date_of_birth', 'phone_number', ) widgets = { 'date_of_birth':DateInput(), } views.py @login_required def EditProfile(request): if request.method == "POST": form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('view_profile') else: form = EditProfileForm(instance=request.user) args ={'form':form} return render(request, 'home/editprofile.html', args) editprofile.html {% extends 'home/base.html' %} {% load crispy_forms_tags %} {% block body %} <div class="row justify-content-center"> <div class="col-6"> <div class="card"> <div class="card-body"> <h3>Edit profile</h3> <form method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Save</button> </form> β¦ -
How to get today week no of year in django
i trying to get today week no of year from datetime import datetime import datetime from time import strftime from dateutil import parser today_date = strftime("%V") today_week = parser.parse(today_date) today_week = today_week.weekday() -
Django is sending me an email about "Invalid HTTP_HOST header"
I have website that using django on DigitialOcean. Django is sending me an email with title Invalid HTTP_HOST header: 'url.ml'. You may need to add 'url' to ALLOWED_HOSTS. But I don't want to add this, I added my own domains and ip address. I have list of questions Why is django sending me this email? Bots are attacking to my site? If so how they do that? How can I prevent this? -
Django Hide Posts in UI per User without affecting database
I have an app that display all newsitems having model like: class NewsItem(models.Model): url = models.CharField(max_length=500, default="",unique=True) title = models.CharField(max_length=500, default="") hacker_news_url = models.CharField(max_length=500, default="") posted_on = models.DateTimeField(default=datetime.now) # posted_on = models.CharField(max_length=100,default="") upvote_count = models.IntegerField(default=0) comment_count = models.IntegerField(default=0) contents=models.TextField(default="") UI: I had already setup the default django authentication to view this page. The ui has hide button for each post. So the problem is if the logged in user hides the post, it must be hidden for that user only (even after page refresh) without deleting from database. How to do that? Help Please! This is my views.py: @login_required(login_url='/accounts/login') def index(request): context={'news_items':NewsItem.objects.all().order_by('posted_on')} return render(request, "hello.html", context) -
Can I use 'boto3' library along with the S3Boto3Storage backend from 'django-storages' library?
I'm using S3Boto3Storage to direct my media storage to AWS S3 by installing pip library django-storages. And I want to add a view for putting rows of DynamoDB and I found that I should install boto3 library. Are these libraries compatible? -
django: how to display image in html_email
this is my html <!DOCTYPE html> {% load static %} <html > <head> <title>Email</title> </head> <body> <br><br><br> <img src="{% static 'logo.png' %}" title="" style="height: 6.1rem;">School Collebes <br><br> <p>To: {{ email }}</p> <p>Your Registration has been approved. Please use this {{ email }} as your username and {{ password }} as your password. You may now start enrolling your student using this link https://....</p> <br><br><br> <h2>REGISTRAR</h2> </body> </html> and this is my admin.py @admin.register(ParentsProfile) class ParentsProfile(admin.ModelAdmin): list_display = ('Father_Email','Fathers_Firstname' , 'Fathers_Middle_Initial', 'Fathers_Lastname', 'Request') ordering = ('Request',) search_fields = ('Request',) actions = ['Send_Email','Send_Email_Disapproved'] def Send_Email(self, request, queryset): for profile in queryset: context = { 'email': profile.Father_Email, 'password': profile.Parent_Password, } html_message = render_to_string('Homepage/email.html',context=context) send_mail(subject="Invite", message='',html_message=html_message, from_email=settings.EMAIL_HOST_USER, recipient_list=[profile.Father_Email]) i just want to display what i desire image in my email_html, but i dont know the reason why i cant display an image. did i something wrong with my code? im pretty sure that the image i declare in my email_html are in correct path.