Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create objects in multiple nested serializer in django
I have 3 models which are related to each other via ManytoMany relation like this: class DemandEvents(models.Model): date = models.DateTimeField(blank=True, null=True) quantity = models.IntegerField(default=0) class DemandFlows(models.Model): events = models.ManyToManyField(DemandEvents) flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kit = models.ForeignKey(Kit, on_delete=models.CASCADE) monthly_quantity = models.IntegerField(default=0) class Demand(models.Model): demand_flows = models.ManyToManyField(DemandFlows) delivery_month = models.DateTimeField(blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) I am trying to create the serializers for this but keep getting confused how to handle the multi-level nesting Serializer.py class DemandEventsSerializer(serializers.ModelSerializer): class Meta: model = DemandEvents fields = "__all__" class DemandFlowsSerializer(serializers.ModelSerializer): class Meta: model = DemandFlows fields = "__all__" class DemandSerializer(serializers.ModelSerializer): demand_flows = DemandFlowsSerializer(many=True) class Meta: model = Demand fields = "__all__" def create(self, validated_data): items_objects = validated_data.pop('form_list', None) prdcts = [] for item in items_objects: i = DemandFlows.objects.create(**item) prdcts.append(i) instance = Demand.objects.create(**validated_data) instance.demand_flows.set(prdcts) return instance How do I add events data to this DemandFlows? -
How can I access the Twitter API in a Celery task?
I can't seem to access the Twitter auth within a celery task as request is not defined. If I use my own account variables the task will run fine but when asking for the authenticated users it errors. Can anyone help? views.py def like(request): liker.delay() return render(request, "home.html") Celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AutoTweetLiker.settings') app = Celery('AutoTweetLiker') app.config_from_object('django.conf:settings') app.conf.update(BROKER_URL='*********', CELERY_RESULT_BACKEND='******') app.autodiscover_tasks() @app.task(bind=True) def liker(self): oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) access_key = request.session['access_key_tw'] access_secret = request.session['access_secret_tw'] oauth.set_access_token(access_key, access_secret) api = tweepy.API(oauth) ....The rest of my function using Twitter API... -
Django change data used in template based on checkbox dynamically
I have a database table that contains sets which each have a unique code. These codes are either 3 or 4 characters long. Sets with codes that are 4 characters long represent extra data that is not really needed and by default I filter out these sets before sending the data to the template. However I would like it so the the user can click a checkbox and display those extra sets in the table on the template. To do this I just an Ajax request to the view to send whether the checkbox is checked or not, and then change the base set data. In the view I use an If statement to decides what data is returned. I have checked and the If statement is working, however the data in the template is not changing. js: function ShowExtraSets(e) { console.log(e.checked) $.ajax({ url: '', type: 'POST', data: { csrfmiddlewaretoken : csrf_token, showExtraSets : e.checked } }); } view: def sets_page(request): if 'showExtraSets' not in request.POST: set_list = Set.objects.extra(where=["CHAR_LENGTH(code) < 4"]).order_by('-releaseDate', 'name') elif request.POST['showExtraSets'] == 'true': set_list = Set.objects.order_by('-releaseDate', 'name') else: set_list = Set.objects.extra(where=["CHAR_LENGTH(code) < 4"]).order_by('-releaseDate', 'name') set_filter = SetFilter(request.GET, queryset=set_list) set_list = set_filter.qs ... -
Django serializer does not throw error for flawed validated data
I am running a django application and I have a simple class-based django-rest CreateView. My problem is that data actually gets created even though I sent flawed data. I am not entirely sure if that's expected behaviour, but I think it shouldn't be. View is simple: class ModelCreate(CreateAPIView): """Create instance""" serializer_class = ModelCreateSerializer queryset = ModelCreate.objects.all() In my serializer I am overwriting the create method for some custom behaviour and I am adding two write-only fields that I need for my data creation: class ModelCreate(serializers.ModelSerializer): """Serialize objects.""" field_extra1 = serializers.CharField(write_only=True, required=True) field_extra2 = serializers.CharField(write_only=True, required=True) class Meta: model = ModelCreate fields = ( "field_extra1", "field_extra2", "field3", "field4", "field5", "field6", "field7", ... ) def create(self, validated_data): """Create obj and relate to other model.""" field_extra1 = validated_data.pop("field_extra1") field_extra2 = validated_data.pop("field_extra2") obj = Model.objects.get(name=field_extra1) relation = obj.objects.filter(name=field_extra2)[0] validated_data["relation"] = relation result = ModelCreate.objects.create(**validated_data) return result My model has many optional fields. field_fk = models.ForeignKey( Model, on_delete=models.CASCADE, related_name="building_objects", ) field_m2m = models.ManyToManyField( Model, default=None, blank=True, ) field3 = models.CharField( max_length=120, null=True, blank=True, ) field4 = models.FloatField( null=True, blank=True, validators=[MinValueValidator(0.0)], ) field5 = models.FloatField( null=True, blank=True, validators=[MinValueValidator(0.0), MaxValueValidator(1.0)] ) field6 = models.FloatField( null=True, blank=True, validators=[MinValueValidator(0.0)], ) field7 = models.FloatField( null=True, blank=True, validators=[MinValueValidator(0.0)], ) Now what … -
Django Serializer subclass inheritance
I can't work out why I am unable to override a field in my Serializer parent class. Here is my model: class AccountHolder(base.BaseModel): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) Here is the parent serializer class: class AccountHolder(serializers.Serializer): name = serializers.SerializerMethodField() def get_name(self, holder): return holder.first_name + " " + holder.last_name And the subclass: class SubAccountHolder(Recipient): effective_from = serializers.SerializerMethodField() def get_effective_from(self, sub_holder): return sub_holder.periods.all() .order_by("-effective_from") .first() .effective_from But when I debug the code it is not even calling the method get_effective_from. What would be the correct way of doing this? -
Django Requests As A Client Side
I have a Django app, which that was working fine for a long time. And I have a request to another application (third party), it was working correctly. But suddenly it stopped and returns the following error. HTTPSConnectionPool(host='HOSTNAME', port=PORT): Max retries exceeded with url: /TO/URL/PATH/ (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f2d2bc42a20>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) but when I do telnet it works fine, it works fine when I do curl request. Please, anyone, have an idea? -
Chart.js conflicting with JQuery
Basically I am new to Chart.js but not new to web developing. I have tested lots of ways but it's just JQuery. Whenever I load the chart normally, I get "Chart is not defined" error by JQuery. If I remove JQuery from the site completely I get no error and I get the chart, but I need JQuery, any ideas? <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js" integrity="sha512-SuxO9djzjML6b9w9/I07IWnLnQhgyYVSpHZx0JV97kGBfTIsUYlWflyuW4ypnvhBrslz1yJ3R+S14fdCWmSmSA==" crossorigin="anonymous"></script> <script> $(function () { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }); </script> <canvas id="myChart" width="400" height="400"></canvas> I used the standard graph … -
How to format time into readable format in Django
I have a send_sms function, but the date format from the message is too long and detailed. I want it to format from 2021-01-24 05:12:21.517854+00:00 into just (5:12PM, 24Jan2021) How can I do it? Thanks! def send_sms(request): z = Test.objects.latest('timestamp') numbers = Mobile.objects.all() message = (f'Test ({z.timestamp})') class Test(models.Model): timestamp = models.DateTimeField(auto_now_add=True) -
Reverse for 'deletedata' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['delete/<int:id>/']
I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> my views.py and urls.py code def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('<int:id>/',views.update_data,name="updatedata") ] -
Launching blender console docker container with Django
I'm making a web application where the user can render an image with blender. I'm using django as the framework and have it running in a docker environment. My question is what would be the best practice to launch blender console commands? and more specifically how do I launch an docker container with arguments that includes the blender console. -
When i execute unittest command "python3 -m unittest filepath/filename.py" it showing improperly configured error
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
How to delete Django migration files in Dokku?
In a normal world, you can access your application folder and delete files and folders. For Django migration files, the following code can be applied: find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete But in Dokku, everything is in a container that I have no idea how to access. So how can I delete migration files? -
Model Design in Django
I have many components and I want to have for each component a list where it shows users have taken how many component class Component(models.Model): name=models.CharField(max_length=128,unique=False,blank=False) detail=models.TextField() max_num=models.IntegerField(default=0) issued_num=models.IntegerField(default=0) def __str__(self): return self.name def save(self,*args,**kwargs): super().save(args,kwargs) def available(self): return self.max_num-self.issued_num Status=((0,"Pending"),(1,"Accepted"),(2,"Rejected")) class Issued(models.Model): request_user=models.ForeignKey(User,on_delete=models.CASCADE) component=models.ForeignKey(Component,on_delete=models.CASCADE) status=models.IntegerField(choices=Status,default=0) request_num=models.IntegerField(default=0) def __str__(self): return self.component.name I have come up with this solution where Issued model depending on status will be shown as request or will be treated confirmation for issue request depending on its status Can anyone please tell whether its right way to do it or if its not suggest database friendly design -
Django view html to pdf executed twice
I have following Class to generate a pdf file where I use django-renderpdf to generate a pdf from a html template. But the view is executed twice and an error is thrown. My class: class WeeklyMetre(PDFView): template_name = 'reports/invoice/weekly_metre.html' allow_force_html = True prompt_download = True @property def download_name(self) -> str: invoice = Invoice.objects.get(pk=self.kwargs['pk']) return f"WeeklyMetre_{invoice.invoice_number}.pdf" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) invoice = Invoice.objects.get(pk=self.kwargs.get('pk')) market_labor_specifications = _getWeeklyMetreData(invoice=invoice) # calculate reported items: reported market_labor_specifications # invoiced specifications which are validated in invoice-period # but labor_date before invoice-period reported_mls = MarketLaborSpecification.objects.filter(invoice_id=self.kwargs.get('pk'), market_labor__labor_date__lt=invoice.period_from) \ .values('market_labor__labor_date', 'specification__position', 'specification__name') \ .order_by('market_labor__labor_date', 'specification__position', 'specification__name') \ .annotate(sum_pos=Sum('validated_quantity')) context.update({ 'invoice': invoice, 'market_labor_specifications': market_labor_specifications, 'reported_mlss': reported_mls }) print('context data', datetime.datetime.now()) return context Between the two excutions I have following error: Exception happened during processing of request from ('127.0.0.1', 57654) Traceback (most recent call last): File "/usr/lib/python3.6/socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.6/socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.6/socketserver.py", line 724, in __init__ self.handle() File "/home/t3tr4ktys/python-virtual-environments/BillOfQuantities/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/home/t3tr4ktys/python-virtual-environments/BillOfQuantities/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer First of all I don't know why it … -
django deploy with gunicorn is worked except static but not work with nginx conf
I'd like to try deploy django server with nginx. however, it did not work. my django setting setting.py ALLOWED_HOSTS = ['my_private_IP','my_public_IP','*'] ... STATIC_URL = '/home/ubuntu/static/' while I execute gunicorn command with config, it worked except static file. gunicorn -c conf/gunicorn_config.py myproject.wsgi gunicorn_config.py conmmand = '/home/ubuntu/venv/bin/gunicorn' pythonpath = '/home/ubuntu/myproject' bind = 'my_private_IP:8069' Then I'd like to deal with static file. After setting nginx conf, the connection kept waiting. This is my nginx conf in /etc/nginx/sites-available and enable server{ listen 80; server_name _; location /static/ { root /home/ubuntu/static/; } location / { include proxy_params; proxy_pass http://my_private_IP:8069; } } I have changed server_name serveral times (localhost, 127.0.0.1, my_private_IP ...), whatever it was, the connection was still stuck. How can fix to connect to the server? And Is my static conf right? Thanks a lot. -
I am unable to load static files in django although i have done everything
in my settings.py file i did STATICFILES_LOCATION='static' STATIC_URL = '/static/' STATICFILES_DIR=[ os.path.join(BASE_DIR,'Kevin/static') ] STATIC_ROOT='static' but in my templates i am unable to load the files the template folder is in root directory whereas static folder is in django root folder named as Kevin which is also in that base folder in my html template i did the {% load static %} i am sharing some code of my template as well so you can have a look {% load static %} <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Kevin - Dashboard</title> <!-- Custom fonts for this template--> <link href="{% static 'vendor/fontawesome-free/css/all.min.css'%}" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="{%static 'css/sb-admin-2.min.css'%}" rel="stylesheet"> -
node.JS / Django - configure Apache / NGINX to run from location
I am using Apache as my frontend VPS / NGINX as backend VPS for node.js / django apps with react.js frontend. I am trying to run my apps from same VPS, but from different locations: e.g.: https://myapps/app1 https://myappps/app2 Previously I have tackled this issue by adding the location in the router of the apps - however I am not sure if this is the best way to do this. Can I actually add the location in the VPS config of NGINX or Apache? # nginx.default server { listen 8020; server_name example.org; location / { proxy_pass http://127.0.0.1:5000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static { root /opt/app/client/build/; } } -
getting JSON of uploaded pdf file in Django
I have uploaded a pdf file in django server from html page, now I want to show the JSON of same file on HTML page in response. Someone please help me in this. -
Querying model field data in template/views without get_object_or_404()
Homefeed is the page where i query all the blogposts In this project, any user that sees a blogpost that they are interest in can submit their interest to the post. 1 user can only submit 1 interest to that blogpost, but they can submit as many interest as they want to different blogposts. Right now in my home.html, I am trying to make it such that if YOU have submitted interest,(aka your interest status is at pending or accept or decline) for that particular blog post, you will see the view interest button instead of the submit interest button. But I am facing a problem because in my views, I am querying for blog_posts = BlogPost.objects.all() and not blog_post = get_object_or_404(BlogPost, slug=slug). As such, how am I able to query whether or not for the particular blogpost, the user has already submitted an interest in my template to determine which button should show in my home.html? Thanks, and also I dont want to change the url at all :) views.py def home_feed_view(request, *args, **kwargs): context = {} blog_posts = BlogPost.objects.all() context['blog_posts'] = blog_posts page = pageFilter(request.GET, queryset=BlogPost.objects.exclude(author_id=request.user.id).order_by('date_updated')) context['page'] = page paginated_page = Paginator(page.qs, 4) page = request.GET.get('page') page_obj = … -
how can i open a modal from views.py in django? Is there any way?
I have a django application. when a user clicks the submit button two modals should be shown one after another each has to do different functions in views.py in my django app. I am trying to write the code but the problem is not easy and I have looked everywhere and couldn't get the answer. I have to write the code in the following way: views.py def submit(request): #first modal should pop up which has two options. #secound modal should pop up which also has a two options. and when the user clicks any of the buttons each should also call the different function in views.py. html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <button class="btn btn-danger custom" style="position:absolute; left:800px; top:180px;" type="submit">Update the data</button> # user clicks a button in form and modal should pop up # then 2 modals should pop up # the first modal has two buttons # when user clicks the update button the function in the views should be called and also 2nd modal should pop up <!--modal 1--> <div aria-hidden="true" aria-labelledby="exampleModalLabel" class="modal fade" id="UpdateModal" role="dialog" tabindex="-1"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Update Changes</h5> <button aria-label="Close" class="close" data-dismiss="modal" … -
is it possible to create the link of selenium file and insert jquery?
I have created a Python Selenium script in Django framework. I want to manage the link of my selenium project. So that whenever I hit the link in a browser, it should run testing. I don't want to run it from the terminal, as I want to add jquery. here is my code driver = webdriver.Chrome(executable_path='/home/sr/PycharmProjects/selenium/automation/KPTGR/chromedriver') driver.get("https://www.google.com/") get = driver.find_element_by_id("gsr") print(get.text) -
How to short down this code to create django model so it works the same in term of functionality
Just imagine Netflix Site, I want to store video links of multiple seasons of TV shows with multiple episodes, I want to increment number of seasons and episode of a certain tv show on the need specifically from admin area. I don't know ho to do that instead of just creating variable of every episode link and season model. Please Help ! Thanx in adv class Tv_Shows(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() episode1 = models.CharField(max_length=100, null=True) episode2 = models.CharField(max_length=100, null=True) episode3 = models.CharField(max_length=100, null=True) episode4 = models.CharField(max_length=100, null=True) episode5 = models.CharField(max_length=100, null=True) episode6 = models.CharField(max_length=100, null=True) episode7 = models.CharField(max_length=100, null=True) episode8 = models.CharField(max_length=100, null=True) episode9 = models.CharField(max_length=100, null=True) episode10 = models.CharField(max_length=100, null=True) imdb_rating = models.DecimalField(null=True, max_digits=12, decimal_places=1) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views = models.IntegerField(default=0) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. tags = TaggableManager() -
How to set up a homepage at django
I am new to django and I want to set my homepage url My homepage is 127.0.0.1:8000/home but I want my homepage at 127.0.0.1:8000/ or I want my django start as 127.0.0.1:8000/home as default. How do I do it? -
unable to upload multi files through django serializer
I can upload single files at a time but cant upload multiple files at once. Any idea how can I upload multifiles ? my models.py class VideoPost(models.Model): user = models.ForeignKey("profiles.HNUsers", on_delete=models.DO_NOTHING) video = models.FileField("Post Video", blank=True, null=True) timestamp = models.DateTimeField("Timestamp", blank=True, null=True, auto_now_add=True) text = models.TextField("Description text", blank=True) class Meta: verbose_name_plural = "VIdeo Posts" my serializers.py class VideoPostSerializer(serializers.ModelSerializer): class Meta: model = VideoPost fields = ( 'user', 'text', 'video', ) and my views.py def video_post(request): if request.method == 'POST': data = request.data print(data) serializer = VideoPostSerializer(data=data , many =True) if serializer.is_valid(): serializer.save() print("audio object saved") try: video_post_object = VideoPost.objects.filter(user__id=data['user']).order_by('-timestamp')[0] print(video_post_object) try: post = Posts() #testing multi files post.user = HNUsers.objects.get(id=data['user']) post.audio_url = video_post_object.video.url post.type = 'V' post.category = data['category'] post.created_on = video_post_object.timestamp post.text = video_post_object.text save_post = post.save() post_id = post.pk try: user = HNUsers.objects.get(pk=data['user']) if user.user_type == 'HN': payload = { "user_name": user.full_name, "image_url": user.profile_img_url, "post_id": post_id, "notification_type": "hn" } print(payload) broadcast_notification('all', payload, 1) except HNUsers.DoesNotExist: print("user_id_does_not_exist") print("post object created") except Posts.DoesNotExist: print("Failed - post creation failed") except HNUsers.DoesNotExist: print("Failed - user object not found") except AudioPost.DoesNotExist: print("Failed - video object not found") return Response(serializer.data, status=status.HTTP_200_OK) -
Celery: Sending email using the Celery throws "Invalid address" error
I am using Django + Celery to send emails. I am basically new to Celery. Whenever I try to send emails using the tasks.py file it shows me following error on console. backends/smtp.py", line 122, in _send recipients = [sanitize_address(addr, encoding) for addr in email_message.recipients()] **File "/home/ropali/Development/PythonWorkSpace/hrms_venv/lib/python3.9/site-packages/django/core/mail/**backends/smtp.py", line 122, in recipients = [sanitize_address(addr, encoding) for addr in email_message.recipients()] File "/home/ropali/Development/PythonWorkSpace/hrms_venv/lib/python3.9/site-packages/django/core/mail/message.py", line 84, in sanitize_address raise ValueError('Invalid address "%s"' % addr)ValueError: Invalid address "['test2@test.com']" My tasks.py file import string from django.contrib.auth.models import User from django.utils.crypto import get_random_string from celery import shared_task from hrms.services import EmailService from django.conf import settings @shared_task def send_marketing_email(email, subject): email_service = EmailService(subject=subject, to=email) # email_service.set_to(email) email_service.load_template('templates/marketing_email.html',context={ 'url': settings.BASE_URL + 'pages/contact-us' }) email_service.send() return 'Email sent to {}'.format(email) My view code: class SendEmailsView(LoginRequiredMixin, AdminRequired,View): template_name = 'marketing/send_emails.html' context = {} def get(self, request): return render(request, self.template_name, self.context) def post(self, request): subject = request.POST.get('subject') if not subject: return JsonResponseBuilder.error('Subject field is required.',HTTPStatus.UNPROCESSABLE_ENTITY.value) # get all the names & emails from the uploaded excel file # send the email to each email address from the file email_df = pd.read_csv(settings.MEDIA_ROOT / constants.EMAIL_LEADS_EXCEL_FILE) for index,row in email_df.iterrows(): send_marketing_email.delay(row['email'], subject) return JsonResponseBuilder.success('Emails sent successfully...') services.py file which contains EmailService class. class EmailService(): email …