Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django project setup issue with the command : django-admin startproject xxxxxx
I started coding in python - Django just few days ago .I am using windows 10 . I installed Django project with pip and virtual env. but when I give this command : django-admin startproject xxxxxx the console is showing : Command not found: django-admin.py Please help me to solve the issue. -
Error of Django NoReverseMatch at /top/ although being designated name of url
I got an error NoReverseMatch at /top/ and I cannot fix it. I got an error like Reverse for 'create_users' not found. 'create_users' is not a valid view function or pattern name. My application structure is login -urls.py -views.py app -urls.py -views.py -settings.py templates -app -top.html -users -login.html users -urls.py -views.py I wrote code urls.py of login from django.urls import path, include from . import views urlpatterns = [ path('login/', include('registration.urls')), path('create_users/', views.Create_users.as_view(), name="create_users"), ] I wrote code views.py of login class Create_users(CreateView): def post(self, request, *args, **kwargs): form = UserCreateForm(data=request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('user_id') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('/') return render(request, 'create.html', {'form': form,}) def get(self, request, *args, **kwargs): form = UserCreateForm(request.POST) return render(request, 'create.html', {'form': form,}) create_users = Create_users.as_view() Furthermore I wrote code in templates/app/top.html <html lang="ja"> <body> {% if user.user_id %} <p>Hello,{{ user.user_id }}</p> {% else %} <a href="{% url 'users_index' %}">Click here</a> <a href="{% url 'create_users' %}">Create user</a> {% endif %} </body> </html> I rewote templates/app/top.html,I added app_name="login" in urls.py of login like <a href="{% url 'login:create_users' %}">Create user</a> but another error happens. I designated name of url,but NoReverseMatch error happens. What is wrong in my code? -
Apache, mod-wsgi: Any URL is served by project, ServerName is ignored
I am setting up a Django project and Apache on Ubuntu 20. The below setup correctly displays the Django project, however ANY URL that points to the server's IP address is served this project. I obviously need to limit this to my particular website mysite.com. ServerName is ignored. I have looked at other question/answers. However, they usually mention httpd.conf, which is no longer used in Apache. Or, there is no accepted answer. Or, it just isn't relevant to my setup. Also, I've been told not to touch apache2.conf. This is a brand-new installation instance so no weird stuff hanging around. I will eventually need to have multiple sites served on the same server. Install Apache mod-wsgi: sudo apt install apache2 apache2-utils ssl-cert libapache2-mod-wsgi sudo a2enmod rewrite sudo systemctl restart apache2 Set up .conf file and activate it: Copy mysite.com.conf to /etc/apache2/sites-available sudo a2ensite mysite.com.conf sudo a2dissite 000-default.conf sudo systemctl reload apache2 sudo systemctl restart apache2 mysite.com.conf: <VirtualHost *:80> WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess test_project_ns processes=1 threads=10 python-path=/home/ubuntu/test_project python-home=/home/ubuntu/test_project/test_env WSGIProcessGroup test_project_ns ServerAdmin webmaster@localhost DocumentRoot /var/www/html ServerName mysite.com ServerAlias www.mysite.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/ubuntu/test_project/test_ui> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/ubuntu/test_project/test_ui/wsgi.py </VirtualHost> Result: mysite.com correctly serves up the … -
I want to use css styling in pycharm using django framework
I want to use css styling in pycharm using django framework. On running it, no error occurs but it also does not show any of the styling being done. Does pycharm support css stylesheet? here is my code: style.css : body{ background: pink url("images/background.png"); } index.html : {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}" /> {% if all_albums %} <h3>here are all my albums:</h3> <ul> {% for album in all_albums %} <li><a href = "{% url 'music:detail' album.id %}"> {{ album.album_title }}</a></li> {% endfor %} </ul> {% else %} <h3>You don't have any Albums</h3> {% endif %} detail.html : <img src="{{ album.album_logo }}"> <h1>{{ album.album_title }}</h1> <h2>{{ album.artist }}</h2> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'music:favorite' album.id %}" method="post"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ song.id }}"> <label for="song{{ forloop.counter }}"> {{ song.song_title }} {% if song.is_favorite %} <img src="#"/> {% endif %} </label><br> {% endfor %} <input type="submit" value="Favorite"> </form> -
Mock class attribute with side_efffect
How can I raise exceptions while accessing an attribute of the mocked object? I have tried to do the same with the following snippet, import unittest from unittest import TestCase from django.core.exceptions import ObjectDoesNotExist from unittest.mock import MagicMock, PropertyMock def function_to_call_one_to_one(model_instance): try: return model_instance.artist.name except ObjectDoesNotExist: # calling `model_instance.artist` will raise `ObjectDoesNotExist` exception return "raised `ObjectDoesNotExist`" class TestObjectDoesNotExist(TestCase): def test_artist_name(self): model_instance = MagicMock() model_instance.artist.name = "Michael Jackson" name = function_to_call_one_to_one(model_instance) self.assertEqual(name, "Michael Jackson") def test_artist_name_with_error(self): model_instance = MagicMock() model_instance.artist = PropertyMock(side_effect=ObjectDoesNotExist) res = function_to_call_one_to_one(model_instance) self.assertEqual(res, "raised `ObjectDoesNotExist`") if __name__ == '__main__': unittest.main() Unfortunately, the test function, test_artist_name_with_error(...) has failed with message, AssertionError: <MagicMock name='mock.artist.name' id='140084482479440'> != 'raised ObjectDoesNotExist' How can I write the unit-test for this case? Note: I have seen this SO post, Python: Mock side_effect on object attribute, but, it doesn't work for me. I hope, this example is a reproducible one. -
Using AJAX with a Django MultipleChoiceField with multiple checkboxes
I'm sending the data from a form with MultipleChoiceField via AJAX and in the template I have multiple checkboxes. I am having problems sending the selected checkboxes. My first attempt was this: var selected =[]; $('.checkboxes:checked').each(function(){ selected.push($(this).val()) }); and then in $.ajax: data: { email : $('[name=email]').val(), country: $('[name=country]').val(), category: selected, but this didn't work. After this I tried to send in the selected values as a string and then just split them and create a list in the view. I managed to do that but I now can't figure out on how to replace the value of the field in the form. form = SubscriberForm(request.POST) categories = form['category'].value() category = categories[0].split(',') del category[-1] form.instance.category = category I'm not sure as to why this doesn't work. I even tried setting a dummy string just to see if the problem was with my category variable but that didn't work either. -
Column core_event.hometask does not exist
When I run my Django project on production server, I have this error: ProgrammingError at /admin/core/event/ column core_event.hometask does not exist LINE 1: ..._event"."is_approved", "core_event"."event_type", "core_even... What I should do to fix it? Now I haven't "hometask" field in my model: class Event(models.Model): name = models.CharField(max_length=100, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) description = models.TextField(max_length=1000, blank=True, null=True) date_start = models.DateTimeField(null=True, blank=True) date_finish = models.DateTimeField(null=True, blank=True) image = models.ImageField( upload_to="event_images/", default='event_images/default.png', blank=True, null=True) is_approved = models.BooleanField(null=True) TYPE_CHOICES = ( ('Event', "Мероприятие"), ('Lesson', "Урок"), ) event_type = models.CharField(choices=TYPE_CHOICES, max_length=200, default="Мероприятие") topics = ArrayField(models.CharField(max_length=200), blank=True, null=True) materials = ArrayField(models.URLField(), blank=True, null=True) possible_users = models.ManyToManyField("core.User", blank=True, related_name='possible_users') actual_users = models.ManyToManyField("core.User", blank=True, related_name='actual_users') classes = models.ManyToManyField("core.Class", blank=True, related_name='classes') -
Django - ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
i have a really trange problem, when i run my django server, even the simplest one it calls this error once every like 1 minute. ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine. The thing is, nothing is breaking. Server is running fine. I've tried to trun off firewall but it didnt help and also when i turned off my antivirus program, it still makes this error. I have newest version of python and django installed. Does anybody know how to fix this? I've searched for over one day for this problem solution, but i didnt find anything helpful. -
Passing HTML tags with Python
i'm currently working on a proyect that involve "markdown2" librarie to transform .MD files to HTML tags. Almost everything works, but when i render HTML file in python and throw the content of .MD file converted, it just shows the literal tags. Here is the function that converts MD files to HTML tags: def get_entry(title): try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None And here is the function that pass those HTML tags and render the HTML file: def entry(request, title): entry = markdown(util.get_entry(title)) return render(request, "encyclopedia/entry.html", { "entry" : entry }) Here is the HTML file: {% extends 'encyclopedia/layout.html' %} {% block title %} {% endblock %} {% block body %} {{ entry }} {% endblock %} In the browser it shows the HTML file withe converted MD files like this: enter image description here ¿How can i pass those HTML tags so the browser understand that they are tags and not strings? -
Filtering a Boolean field
Trying to filter boolean field, but it brings the error :too many values to unpack (expected 2) Here is the code def index(request): if not request.session.has_key('currency'): request.session['currency'] = settings.DEFAULT_CURRENCY setting = Setting.objects.get(pk=1) category = Category.objects.all() products_latest = Product.objects.all().order_by('-id')[:4] # last 4 products products_slider = Product.objects.all().order_by('id')[:4] # first 4 products products_picked = Product.objects.all().order_by('?')[:4] # Random selected 4 products products_promoted = Product.objects.filter('promote=True')[:7] # The error origin class Product(models.Model): title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) promote = models.BooleanField(default=False) description = models.TextField(max_length=255) image = models.ImageField(upload_to='images/', null=False) price = models.DecimalField(max_digits=12, decimal_places=2, default=0) minamount = models.IntegerField(default=3) Why is it bringing the error and how do i fix it ? -
Why is Huey running all historic task all of a sudden?
We have an old setup with older django and huey queue using Redis. Everything was working fine with few minor bumps until now. Huey now decided to rerun all of the historic tasks for no reason as far as I can tell. Here's the config I'm using HUEY = { 'name': 'serafin', 'store_none': True, 'always_eager': False, 'consumer': { 'quiet': True, 'workers': 100, 'worker_type': 'greenlet', 'health_check_interval': 60, }, 'connection': { 'host': 'localhost' if DEBUG else '...cache.amazonaws.com', 'port': 6379 } } Where should I look for reasons? How can this be prevented? -
How to do a translator?
I am currently coding my first website, which is a translator in an invented language. You input a random phrase and it should get translated in the invented language. Here's the code for the translation: class TranslatorView(View): template_name= 'main/translated.html' def get (self, request, phrase, *args, **kwargs): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" return render(request, 'main/translator.html', {'translation': translation}) def post (self, request, *args, **kwargs): self.phrase = request.POST.get('letter') translation = self.phrase context = { 'translation': translation } return render(request,self.template_name, context ) Template where you input the phrase: {% extends "base.html"%} {% block content%} <form action="{% url 'translated' %}" method="post">{% csrf_token %} <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" name='text' id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> {% endblock content %} Template where … -
How to Insert HTML code to database using json and django?
I am trying to add HTML template code directly into database in django-rest-framework. And want to use json as retrieve and add the html code. How can I do this? class AddHTML(models.Model): template_name = models.CharField(max_length=50, default="") HTML_code = models.TextField(default="") def __str__(self): return self.template_name serializer.py class AddHTMLSerializer(serializers.ModelSerializer): class Meta: model = AddHTML fields = '__all__' views.py class HTMLData(APIView): def get(self, request, format=None): html = AddHTML.objects.all() serializer = AddHTMLSerializer(html, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = AddHTMLSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class HTMLDataDetail(APIView): def get_object(self, id): try: return AddHTML.objects.get(id=id) except AddHTML.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) def get(self, request, id, format=None): html = self.get_object(id) serializer = AddHTMLSerializer(html) return Response(serializer.data) def put(self, request, id, format=None): html = self.get_object(id) serializer = AddHTMLSerializer(html, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, id, format=None): html = self.get_object(id) html.delete() return Response(status=status.HTTP_204_NO_CONTENT) Here in views what should I do that without loosing any tags of HTML data I could easily save and retrieve from database. Kindly reply soon -
How do deploy GeoDjango wit Postgres using Elastic Beanstalk Application
I am trying to Deploy the GeoDjango Application with Postgres on AWS Elastic Beanstalk. But it get stuck in GDAL on Amazon Linux 2 and Python 3.7. -
Django: Class has no 'objects' member
models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title views.py from django.shortcuts import render from .models import Post def meldungen(request): context = { 'posts': Post.objects.all() } return render(request, 'web/meldungen.html', context) Top: There is the Error in line 4: *Class 'Post' has no 'objects' member - pylint(no-member). I tried to migrate it an the problem wasn't solved. But in the django docs i read: If you don’t add your own Manager, Django will add an attribute objects containing default Manager instance. ( https://docs.djangoproject.com/en/3.0/ref/models/class/ ) I read all StackOverflow Posts for this problem but no solution worked. I (i use VSC) tried installing pylint-django, reinstalled pylint and pip .... But here it looks like there isn't just an linter warning, because on the server (Debug is true) appears this error: Error during template rendering In template C:\(...)\web\templates\web\base.html, error at line 9 int() argument must be a string, a bytes-like object or a number, not'NoneType' In this line: If i comment the error line in the view.py file out the site works without any errors. Also i tried render the … -
Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found. i have installed letest postgres setup psycopg2 installed -
Django with Apache grab user from client
I have some computers into domain and I want to automatically login using Active directory credentials I've made some research over the internet and I found a module for Apache named mod_authnz_sspi. First I made a test using a PHP project and he work (I was able to grab the user from the client) but when I tried on Django doesn't work... This is my configuration Apache 2.4 ... LoadModule authn_core_module module/mod_authn_anon.so LoadModule authz_core_module module/mod_authz_dbd.so LoadModule authnz_sspi_module module/mod_authnz_sspi.so <Location "path_to_django_project"> AuthName "Test" AuthType SSPI SSPIDomain "MY.DOMAIN" SSPIAuth on SSPIOfferSSPI on SSPIAuthoritative on SSPIUsernameCase lower SSPIOmitDomain on require valid-user </Location> <VirtualHost *:80> <Directory "path_to_project"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / "path_to_wsgi" </VirtualHost> Django - settings.py MIDDLEWARE = [ ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', ... ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend ] - views.py def testing(request): user = request.META['REMOTE_USER'] return HttpResponse(user) What error I receive: Exception Type: KeyError Exception Value: 'REMOTE_USER' Sorry for my english! -
Links repeated in Django Rest Framework
this is driving me nuts! I hope you can help me. I'm trying to get 2 views for the same model (I need one just like in the model and the other one like another app needs it). I have created 2 serializers, 2 views and 2 urls but when I check they are repeated! I'll try to show you the relevant part of the code: urls.py from consumptions.routers_views import MessageViewSet, MessageSapViewSet router.register(r'messages', MessageViewSet) router.register(r'messagesforsap', MessageSapViewSet) routers_views.py from .serializers import MessageSerializer, MessageSapSerializer class MessageViewSet(viewsets.ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [DjangoFilterBackend] filter_fields = ['user','date','consumption','content','read', 'deleted'] class MessageSapViewSet(viewsets.ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSapSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [DjangoFilterBackend] filter_fields = ['user','date','consumption','content','read', 'deleted'] serializers.py class MessageSerializer(serializers.HyperlinkedModelSerializer): consumption = ConsumptionSerializer(allow_null=True) user = UserSerializer(allow_null=True) class Meta: model = Message fields = [ "id", "user", "date", "consumption", "content", "read", "deleted" ] class MessageSapSerializer(serializers.ModelSerializer): user = UserSerializer(allow_null=True) class Meta: model = Message fields = [ "user", "date", "content", "read", "deleted" ] My problem is that when I check the links in the main page of the api I find that links are repeated -
Django REST Framework, only Admin can DELETE or PUT
I'd like to ask how I can control object permissions within Django Rest Framework with the effect that: User has no ability to DELETE nor PUT Admin is a User that also can DELETE and PUT In order access API / SAFE_METHODS User must be Authenticated I have tried standard permissions, such as permissions.IsAdminUser and IsAuthenticatedOrReadOnly, but no match. Is there a standard Permission to achieve below? If not, what is the best next step, to control permissions via Django models or via DRF? | API end-points | HTTP Method | Authenticate | Permissions | Result | |---------------------- |------------- |------------ |------------ |------------------------------------------ | | /products | GET | User | User | List of product | | /products | POST | User | User | Create new product | | /products/{product_pk}| GET | User | User | Retrieve details of particular product | | /products/{product_pk}| PUT | Admin | Admin | Fully update particular product's info | | /products/{product_pk}| PATCH | User | User | Partially update particular product's info | | /products/{product_pk}| DELETE | Admin | Admin | Delete particular product's details from DB | Serializers.py class ProductSerializer(HyperlinkedModelSerializer): class Meta: model = Product fields = '__all__' views.py class ProductView(viewsets.ModelViewSet): … -
Cannot filter my Django model depence on created_date
I am trying to do a chart. My database has created_date. I am getting product data every day about 150 times and I want to see a daily increase and decrease of my data. I have no problem with my front end and Django-template (I try manual data and it works well) I just want to see the last 7 days chart. When I use Products.objects.filter(created_dates=days) filter method I am getting empty Queryset. I already try created_dates__gte=startdate,created_dates__lte=enddate it return empty Queryset to. I also try created_dates__range to there is no answer too. I just get data from created_dates__gte=days but I don't want these data. view.py from datetime import date,timedelta import datetime def data_chart(request): data = [] week_days = [datetime.datetime.now().date()-timedelta(days=i) for i in range (1,7)] for days in week_days: product_num = Products.objects.filter(created_dates=days) date =days.strftime("%d.%m") item = {"day": date,"value":len(product_num)} data.append(item) return render(request, 'chartpage.html', {'data': data}) In my database, I have thousands of data and my daily data about 150. My created_dates column format like this. created_dates col: 2020-10-19 09:39:19.894184 So what is wrong with my code?. Could you please help? -
Is mixing a class and a function based views in Djago an acceptable practice?
My project is using class based views, but I can't build a custom 500 error page using this approach. Using class based view: client_interface/views/errors/server_error_view.py: from django.shortcuts import render from django.views import View class ServerErrorView(View): def get(request): return render(request, "client_interface/errors/500.html") urls.py: from client_interface.views.errors.server_error_view import ServerErrorView handler500 = ServerErrorView.as_view() It always returns ?: (urls.E007) The custom handler500 view 'client_interface.views.errors.server_error_view.ServerErrorView' does not take the correct number of arguments (request). I've tried to change arguments of the get method to (self, request), or (*args), but the error remains the same. From the other hand if I use function based view: client_interface/views/errors/server_error_view: from django.shortcuts import render def custom_error_view(request): return render(request, "client_interface/errors/500.html", {}) urls.py handler500 = 'client_interface.views.errors.server_error_view.custom_error_view' Everything works fine. So now, I'm wondering if it's acceptable to have one function based view, and the rest of the application will be class based, or is it a crime in django world. -
401 Client Error: Unauthorized for url: https://graph.microsoft.com/v1.0/users/mehdi.aouinti@infinitymgt.fr/sendMail
401 Client Error: Unauthorized for url: https://graph.microsoft.com/v1.0/users/mehdi.aouinti@infinitymgt.fr/sendMail | Error Message: {"error":{"code":"NoPermissionsInAccessToken","message":"The token contains no permissions, or permissions can not be understood.","innerError":{"requestId":"74651b2c-4e87-4365-a1b3-b177bd5b8848","date":"2020-10-19T11:52:02"}}} -
TypeError Django at /add_items/HTML Page
Getting this error on the page : TypeError at /add_items/ str returned non-string (type NoneType) Request Method: GET Request URL: http://127.0.0.1:8000/add_items/ Django Version: 3.0.7 Exception Type: TypeError Exception Value: str returned non-string (type NoneType) views : def add_items(request): form = StockCreateForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') z=messages.success(request, 'Successfull') print(z) return redirect("admin.home") context = { "form": form, "title": "Add Item", } return render(request, "hdm_template/add_items.html", context) Html Page: {% extends 'hdm_template/base_template.html' %} {% block page_title %} Add Item {% endblock page_title %} {% block main_content %} {% load static %} {% load crispy_forms_tags %} <section class="content"> <div class="wrapper"> <div class="row"> <div class="col-md-12"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Add Item</h3> </div> <!-- /.card-header --> <!-- form start --> <form method='POST' action=''> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.category|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.item_name|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.quantity|as_crispy_field }} </div> </div> <input class="btn btn-primary" type="submit" value='Save'> </form> </div> <!-- /.card --> </div> </div> </div><!-- /.container-fluid --> </section> URL: path('add_items/',HDMViews.add_items,name='add_items'), I cant understand where it went wrong -
Illegal instruction(core dumped) tensorflow python3.8 ubuntu 16
I am facing such problem Illegal instruction(core dumped) tensorflow python3.8 ubuntu 16 Python 3.8.3 (default, May 14 2020, 22:09:32) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import tensorflow as tf Illegal instruction (core dumped) -
How to speed up the execution time of sending mass emails with django EmailMultiAlternatives and get_connection method?
I'm using a mass mail function for sending mails to about 50 users. Once I sent the api call it should update the details in DB and loop the users and get the template_context based on the type of user by using EmailMultiAlternatives. Appending the results to a list and using the list to send mails by using get_connection(). The function works good. But the processing time is large because of which the function cannot send the response back within the time. def sample_function(get_request): recipient_list = [] #update DB tables for users in To_recipients: recipient_list = get_context(user) for users in Cc_recipients: recipient_list = get_context(user) success = send_mail(recipient_list) def get_context(user_type) if user_type == 'To': #some context elif user_type == 'Cc': #some context else #some context #After getting context template = render_to_string('sample.html', context=context) message = EmailMultiAlternatives(subject, message, from, to]) message.attach_alternative(template, 'text/html') return message def send_mail(mail_list): from django.core.mail import get_connection, EmailMultiAlternatives connection = connection or get_connection( username=user, password=password, fail_silently=fail_silently) return connection.send_messages(mail_list) I'm not familiar with django, please do the needful. Thanks in advance!!