Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bidirectional communications with web Server and ESP 8266
I am working on a project that has ESP 8266 to send data to a web server as well as recieve a feedback from the server based on the data I sent. I have not been able to do this. Please help me out. If don't mind you can email edenwannaji1980@gmail.com -
Django Concat columns with integers and strings
I have run into an issue using attempting to add values from two different columns together in a query, namely that some of them contain numbers. This means that the built in Concat does not work as it requires strings or chars. Considering how one can cast variables as other datatypes in SQL I don't see why I wouldn't be able to do that in Django. cast(name as varchar(100)) I would assume that one would do it as follows in Django using the Concat function in combination with Cast. queryset.annotate(new_col=Concat('existing_text_col', Cast('existing_integer_col', TextField())).get()) The above obviously does not work, so does anyone know how to actually do this? The use case if anyone wonders are sending jenkins urls saved as fragments as a whole. So one url would be: base_url: www.something.com/ url_fragment: name/ url_number: 123456 -
Django HTML template database query doesn't show anything
I'm trying to query some data and insert it into my HTML template. My model looks like this class Usertasks(models.Model): TaskID = models.CharField(max_length=40) user = models.CharField(max_length=40) TaskStatus = models.CharField(max_length=10) And I have a view that has the following content from callgolem.models import Usertasks def dashboard(request): query_results = Usertasks.objects.all() if not request.user.is_authenticated: return redirect('/account/login/') return render(request, 'dashboard.html') and in my html template I wrote this <div class="tasks-list"> <div> {% for item in query_results %} <p>{{ item.user }}</p> <p>{{ item.TaskID }}</p> <p>{{ item.TaskStatus }}</p> {% endfor %} </div> </div> However when i'm loading the webpage the query is blank. Nothing is shown. I opened my DBviewer and made sure that there's actual data in what im trying to query. -
How to properly document query params(search, filtering) Django Rest Framework?
I'm new at rendering documentation for DRF. I can not understand how to properly document it in code to render descriptions at documentation. I'm using DRF Docs for it. For example: I have route where i can retrieve some data. At related view i have: search_fields = ('name', 'registration_date') But those fields have no descriptions at documentation page. . So i want to add a descriptions for them. Is there a way to do it? -
Understanding uWSGI in the context of PHP
I have worked mostly with PHP and to some extent with Java. And currently looking at Python and Django. When a Django project is deployed on production, it is required to choose one of servers that implement wsgi specification. The definition is pretty straight forward as well as history. Looking back at php world I don't see a parallel with wsgi and that creates some confusion and probably an opportunity to learn more about it. So the questions is what makes python application special that they require (frameworks as well as servers) to implement wsgi specification ? Do we have similar specification for php ? any reasons for having/having not ? Probably a unique issue with python ? however, I see we can use uWSGI with php applications also. Is wsgi is something similar to Java Servlet specification ? and uWSGI server is like Tomcat i.e Application Server. If we consider a wsgi server as Application Server, what services it does provide e.g manage security, transaction processing, resource pooling, and messaging or more/all of them ? -
Can not load data when using autocomplete in Django
Trying to use autocomplete in Django I face the problem that I can not load my data to the desired textfield in my template. I follow the tutorial from here: https://django-autocomplete-light.readthedocs.io/en/3.1.3/tutorial.html My view.py class ProductAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Product.objects.none() qs = Product.objects.all() if self.q: qs = qs.filter(product_name__contains=self.q) return qs My models.py class Product(models.Model): product_id = models.CharField(max_length=30, blank=True, null=True,unique=True) product_name = models.CharField(max_length=60, blank=True, null=True) My forms.py class ProductForm(ModelForm): product_name = ModelChoiceField(queryset=Product.objects.all(),widget=autocomplete.ModelSelect2(url='product-autocomplete')) class Meta: model = Product fields = ('__all__') My urls.py url(r'^product-autocomplete/$', views.ProductAutocomplete.as_view(),name='product-autocomplete'), My template.html <div> <form action="" method="post"> {% csrf_token %} <input id="product_name" type="text" name="product_name" class="form-control" placeholder="type a product:" > </form> </div> <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> {{ form.media }} I have imported static and I checked that the db returns data when I access the /product-autocomplete/ url. The difference from tutorial is that I want to use a textfield and not a form. Moreover, I used the absolute path for loading jquery.js file and the problem remains. Any idea why I can not load the product names inside my textfield in order to have an autocomplete textfield? -
Django allauth, require email verification for regular accounts but not for social accounts
So I'm using django-allauth, even though I've found a previous post pointing to the configuration settings for setting the email verification settings, it looks like it's not working for me. After using their facebook account to login, the user redirected to the e-mail verification form, I would like them to be signed in and be redirected to their profile page. I have the following settings; settings.py ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_FORMS = { 'signup': 'app.users.forms.CustomSignupForm', } SOCIALACCOUNT_PROVIDERS = { 'facebook': {'METHOD': 'oauth2', 'SCOPE': ['email','public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'nl_NL', 'VERIFIED_EMAIL': True, 'VERSION': 'v2.4'} } SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' Even though I understand it is possible for facebook users to have an account without a validated e-mail adres I would still like the facebook users to be automatically logged in after signing in with their facebook account. requirements.txt python == 3.7 django == 2.1.3 django-allauth == 0.38.0 -
FieldTracker throws AttributeError in post_save signal while tying to get changed() fields
I have been trying to make use of the FieldTracker in my project to track the fields that has been updated from within a post_save signal. Initially I thought of using django-dirtyfields, but since it did not support django 2.1, I had to resort to django-model-utils. Below is the project setup customer/apps.py from django.apps import AppConfig class CustomerConfig(AppConfig): name = 'customer' def ready(self): import customer.signals customer/models.py from model_utils import FieldTracker class CreatedByModel(models.Model): created_by = models.ForeignKey(User, blank=True, null=True) modified_by = models.ForeignKey(User, blank=True, null=True) class Meta: abstract = True class Customer(CreatedByModel) name = models.CharField(max_length=255) code = models.CharField(max_length=10) customer_tracker = FieldTracker() Including the admin save_model code here since I am explicitly setting the created_by and modified_by fields here, and calling the super class save_model, which I am not sure might be causing the problem customer/admin.py class CustomerAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if not obj.created_by: obj.created_by = request.user else: obj.modified_by = request.user super().save_model(request, obj, form, change) customer/signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import Customer @receiver(post_save, sender=Customer) def notify_api_clients(sender, **kwargs): print('hit inside tracker {}' . format(sender.customer_tracker.changed())) I am receiving an AttributeError error while trying to save a Customer object stating 'FieldTracker' object has no attribute 'changed'. I am … -
python recursive function to convert json to jstree format
What would be the recursive function that would allow me to covert the existing json data into the required format that jstree jquery library requires to make a filesystem in the browser. existing json data [ {"type":"directory","name":"/logs","contents":[ {"type":"directory","name":"calendar","contents":[ {"type":"directory","name":"Aasdasda","contents":[ {"type":"file","name":"calendar.1530651909"} ]} ]} ]} ] Required Format by JQuery library [{ text : "Folder 1", children : [ { text : "Sub Folder 1", }, { text : "Sub Folder 2", } ] }, { text : "Folder 2", children : [] } ]; -
django forms dont return user
hellow i want retunrn user in forms of django but that's get me error: IndentationError: unindent does not match any outer indentation level this is my forms: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): email = forms.EmailField(required = True) class Meta: model = User fields = ( 'username' 'first_name' 'last_name' 'email' 'password1' 'password2' ) def save(self , commit = True): user = super(RegisterForm , self).save(commit = False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user please help me -
How should I change html template in Wagtail bakery demo?
I'm trying to customize this project https://github.com/wagtail/bakerydemo Cannot find how to change header of the site. Tried to edit bakerydemo/bakerydemo/templates/includes/header.html with no effect. I'm using docker for installation. -
Django smart select : how to chain field to multiple level?
class Modeltwo(models.Model): modelone = models.ForeignKey(Modelone) fieldone = ChainedForeignKey( Fieldone, chained_field="modelone__fieldone", chained_model_field="fieldone", show_all=False, auto_choose=True, sort=True ) does not work if i use 'chained_field="modelone__fieldone"'. works only if the chained_field is within the same model. So how to handle these cases? -
Query with multiple annotations slows down
I've got a query which returns users with additional info Here are my simplified models: class Event(..): creator = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='event_creator_set') class Participator(..): status = models.CharField(..) event = models.ForeignKey('events.Event', on_delete=models.CASCADE, related_name='participators_set') user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='participations_set') My method from User Manager: def additional_info(self): from events.models import Participator participated_events_count = Count( 'participations_set', distinct=True, filter=(~Q(participations_set__event__creator=F('id')) & Q( participations_set__status=Participator.PARTICIPATED)) ) return self.get_queryset()\ .annotate(created_events_count=Count('events_set', distinct=True))\ .annotate(followers_count=Count( 'followers_set', filter=(Q(followers_set__is_following=True)), distinct=True)) \ .annotate( participated_events_count=participated_events_count) Everything works great without the last annotate, but when I'm trying to add participated_events_count value - query performed up to 30 seconds -
How can I link multiple customers to an 'Actie-object'?
Here are the imports: from django.db import models from datetime import datetime, timedelta from django.contrib.auth.models import User This is the first class i did define. It is the status of the action (Actie) and it has a status-id and a status-name with a max_length attribute of 5 (todo, doing, done) class Status(models.Model): id = models.IntegerField(primary_key=True) status_naam = models.CharField(max_length=5, default='todo') def __str__(self): return str(self.id) + " - " + self.status_naam This is the class Actie (Action or the action the user determines) wich has an id, an action-name, a action-status wich refers to the table Status here above, an action-publish-date, an ending-date (the deadline) and a user-id wich refers to the table Users django gives me. class Actie(models.Model): id = models.IntegerField(primary_key=True) actie_naam = models.CharField(max_length=150, default='-') actie_status = models.ForeignKey(Status, default=1) actie_aanmaakdatum = models.DateTimeField(default=datetime.now()) actie_einddatum = models.DateTimeField(default=datetime.now() + timedelta(days=1)) actie_gebruiker = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.id) + " - " + self.actie_naam My question now is what do I have to do to link multiple Users to an Actie? Because now I can link only one User to an Actie. -
django allauth different layout if not authenticated
I'm using django with allauth and I need a different layout if the user is not authenticated. In my login.html I cannot use 'extends base.html'. Is this possible without loosing all the features of allauth ? -
Django email saving
ImproperlyConfigured at /accounts/register. Could not create directory for saving email messages: /home/user/Desktop/emails ([Errno 13] Permission denied: '/home/user').It points to this line "user.email_user(subject, message, html_message=message)" in views.register in account. auth.html <form id='registration-form' method='post' action={% url 'accounts:register' %}> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control input-upper" id="fullname" placeholder="John Doe" name="fullname" required><br> <input type="text" class="form-control input-upper" id="username" placeholder="Username" name="username"><br> <input type="email" class="form-control input-upper" id="email" placeholder="Email" name="email" required><br> <input type="text" class="form-control input-upper" id="organization" placeholder="Organization" name="organization" required><br> <input type="password" class="form-control input-upper" id="password" placeholder="Password" name="password1" required><br> <input type="password" class="form-control input-upper" id="password" placeholder="Confirm Password" name="password2" required><br> <small>By registering you agree to our <a href="{% url 'tos' %}">terms and conditions</a></small> <button type="submit" value='register' id='reg-submit-btn' class="btn btn-primary btn-block btn-signup-form">SIGN UP</button> <button type="button" class="btn btn-primary btn-block btn-sign-linkedin" href="{% url 'social:begin' 'linkedin-oauth2' %}?next={{ next }}">Sign up with LinkedIn</button> <p class="text-already">Already have an account? <a href="" >LOGIN</a></p> </div> </form> MOdel Userprofile.py class UserProfile(models.Model): """ Profile for the User Model """ user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='profile', verbose_name='other Details', ) phone = models.CharField(max_length=11, default='', blank=True, null=True) organization = models.CharField(default='', max_length=300, blank=True) referral = models.OneToOneField( Referral, on_delete=models.CASCADE, related_name='profile', verbose_name='profile Details', null=True) email_confirmed = models.BooleanField(default=False) def __str__(self): return self.user.username + '\'s profile' def activate(self): """" Activates account after email is confirmed """ self.email_confirmed = … -
Proper way to get images from Django static folder
In my setting.py I have next code: STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static'), ] STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And in views.py I want to get some of the images inside static folder as follows: for f in ["static/img/logo/contact-form/logo_black.png", "static/img/logo/contact-form/logo_white.png": # the rest of the code But I'm getting an error: "[Errno 2] No such file or directory: '/Users/Admin/Projects/web-dealers/webDealers/static/img/logo/contact-form/logo-black.png'" What am I doing wrong? -
Django function based view get_form_kwargs
I have the following problem. Normally in Djang Class based views the get_form_kwargs method is used to supply the kwargs to the forms init(). For example: class ComponentForm(forms.ModelForm): diameter = forms.ModelChoiceField(queryset=Diameter.objects.all(), label='Diameter') # required=True, class Meta: model = Component fields = [ 'component_type', 'diameter', 'length' ] def __init__(self, *args, **kwargs): circuit = kwargs.pop('circuit') project = kwargs.pop('project') super(ComponentForm, self).__init__(*args, **kwargs) self.fields['diameter'].queryset = Diameter.objects.filter(project=project, material = circuit.material_type) In the example code above, the "circuit" and "project" are supplied by the get_form_kwargs method in the corresponding view. The question is now how to pass these kwargs to the ComponentForm init() using a function based view? -
How to manage a dynamic menu with Django?
I would like to create the links of the menu dynamically based on the Category models. I've used DetailView and ListView for create a list and detail page of a single category and it run fine. Now I would like to see in base.html a new link in a "dropdown" menu every time the user add a new Category. This is base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>{% block head_title %}Test{% endblock head_title %}</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'list_tag' %}">Tag</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Category </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> {% for category in category_list %} <a href="{{ category.get_absolute_url }}">{{ category.category_name }}</a> {% endfor %} </div> </li> </div> </nav> <div class="container"> <!-- INIZIO corpo centrale --> {% block content %} {% endblock content %} <!-- FINE corpo centrale --> </div> … -
django error while creating model with foreighnkey to another model
models.py from django.db import models class Register(models.Model): seeker_name = models.CharField(max_length=32) seeker_email = models.CharField(max_length=32) seeker_password = models.CharField(max_length=32) def __str__(self): return self.seeker_name class AppliedJobs(models.Model): company_name = models.CharField(max_length=256,null=True,blank=True) company = models.IntegerField() user = models.ForeignKey(Register,on_delete=models.CASCADE,related_name='applied_jobs',null=True,blank=True) def __str__(str): return "AppliedJobs" errors: File "/home/soubhagya/Desktop/jobsterapi/seeker/seeker-env/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/soubhagya/Desktop/jobsterapi/seeker/seeker-env/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) File "/home/soubhagya/Desktop/jobsterapi/seeker/seeker-env/lib/python3.6/site-packages/djongo/cursor.py", line 53, in execute params) File "/home/soubhagya/Desktop/jobsterapi/seeker/seeker-env/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 700, in __init__ self.parse() File "/home/soubhagya/Desktop/jobsterapi/seeker/seeker-env/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 783, in parse raise exe from e djongo.sql2mongo.SQLDecodeError: FAILED SQL: CREATE TABLE "details_appliedjobs" ("id" int32 NOT NULL PRIMARY KEY AUTOINCREMENT, "company_name" string NULL, "company" int32 NOT NULL, "user_id" int32 NULL) Version: 1.2.30 when i am creating appliedjobs model with foreign key of Register model it is showing above error. please have a look into my code. -
Problems with Django logout on urls
I'm beginner with Django and I've resolve my problem yet but I want to understand... I've a login page on my app and a logout page, here is it : urls.py: url('deconnexion', views.logout, name='deconnexion'), url('connexion', views.connexion, name='connexion'), views.py: def connexion(request): error = False if request.method == "POST": form = ConnexionForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user: login(request, user) else: error = True else: form = ConnexionForm() return render(request, 'dashboard/connexion.html', locals()) @login_required(login_url='/dashboard/connexion/') def logout(request): django_logout(request) return redirect(reverse(connexion)) If I change place for url : connexion in place of deconnexion, my script don't work... I don't logout me and I'm redirect on the connexion page which is being connected... If somebody have an idea ? P.S : Sorry for my poor english, I'm french... And French with English.... we all know it's complicate... sorry ;) -
django error while using foreignkey in multiple models of single model
models.py from django.db import models class Register(models.Model): seeker_name = models.CharField(max_length=32) seeker_email = models.CharField(max_length=32) seeker_password = models.CharField(max_length=32) def __str__(self): return self.seeker_name class Details(models.Model): photo = models.CharField(max_length=256) name = models.CharField(max_length=256) user = models.ForeignKey(access_models.Register,on_delete=models.CASCADE,related_name='candidate_details',null=True,blank=True) def __str__(str): return self.name class Social(models.Model): social_links = models.CharField(max_length=256) user = models.ForeignKey(access_models.Register,on_delete=models.CASCADE,related_name='candidate_details',null=True,blank=True) errors: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: details.CandidateDetails.user: (fields.E304) Reverse accessor for 'CandidateDetails.user' clashes with reverse accessor for 'Social.user'. HINT: Add or change a related_name argument to the definition for 'CandidateDetails.user' or 'Social.user'. details.CandidateDetails.user: (fields.E305) Reverse query name for 'CandidateDetails.user' clashes with reverse query name for 'Social.user'. HINT: Add or change a related_name argument to the definition for 'CandidateDetails.user' or 'Social.user'. details.Social.user: (fields.E304) Reverse accessor for 'Social.user' clashes with reverse accessor for 'CandidateDetails.user'. HINT: Add or change a related_name argument to the definition for 'Social.user' or 'CandidateDetails.user'. details.Social.user: (fields.E305) Reverse query name for 'Social.user' clashes with reverse query name for 'CandidateDetails.user'. HINT: Add or change a related_name argument to the definition for 'Social.user' or 'CandidateDetails.user'. System check identified 4 issues (0 silenced). here i wants to use ForeignKey both in Details and Social for Register model. but it is giving me above error. please have a look into my code. -
Celery Tasks are not being executed in Celery, SQS on AWS
I have setup my server on AWS Elastic Beanstalk where I need Celery setup. I used SQS with celery as broker. My settings are below. Settings broker_url = 'sqs://{AWS_ACCESS_KEY_ID}:{AWS_SECRET_ACCESS_KEY}@' result_backend = 'django-db' broker_transport_options = { # 'queue_name_prefix': 'celery-dev', 'polling_interval': 0.3, 'region': AWS_REGION } celery.py app = Celery('Ballogy', broker=broker_url, backend=result_backend, include=['ballogyApi.tasks', 'ballogyApi.tasks.cron_tasks', 'test_center_module.tasks']) # Optional configuration, see the application user guide. app.conf.update( result_expires=3600, ) app.conf.task_default_queue = 'celery-dev' app.conf.task_default_exchange = 'celery-dev' app.conf.task_default_routing_key = 'celery-dev' app.conf.broker_transport_options = broker_transport_options When I add some task in queue, my tasked got added successfully in queue which I can see from Message Available count on AWS SQS console. But my message in flight count is always 0 which means celery worker is not reading message queue. I am using Dockers to run my app server and celery worker. Kindly tell me what else I need to run my server. -
Get Objects Not Transacted for Last 3 Months
I'm fairly new to Django. I have two objects in a django project: Transaction and Item. Item can have many Transaction objects. Transaction has date_time and item fields. How can I write a django query to fetch Items that haven't had any transactions in the past 20 days? Thanks in advance. -
EmailMultiAlternatives no connection could be made because the target machine actively refused it
I'm trying to make an ajax request to will generate a password for a user and send them an email with the password. This all works fine, except for the error I'm getting at msg.send() Ajax: <script type="text/javascript"> var frm = $('#retrieveKeyForm'); frm.submit(function (e) { e.preventDefault(); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { console.log('Submission was successful.'); }, error: function (data) { console.log('An error occurred.'); console.log(data); }, }); }); </script> Views.py class GenerateSecretKey(APIView): def get(self, request): #Get email address from request emailaddr = request.GET.get('email') print(emailaddr) #Show the email address(for debugging) min_char = 10 max_char = 12 allchar = string.ascii_letters + string.digits #Generate passsword password = "".join(choice(allchar) for x in range(randint(min_char, max_char))) print("Your password is {}".format(password)) subject, from_email, to = 'Your key is ready!', 'test@test.com', emailaddr html_content = render_to_string('testapp/email.html', {'password':password}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return Response({'Success':'Your key has been generated. Please check your email.'}) Error: ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it