Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST serializer error
I'm defining model serializers to POST a task instance in Django REST. My models are: class Task(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(blank=True, max_length=100) description = models.CharField(blank=True, max_length=300) class Vector(models.Model): id = models.AutoField(primary_key=True) name = models.CharField() class CalculateVector(models.Model): """ Added 1:M relation between Vector and CalculateVector. """ id = models.AutoField(primary_key=True) task_id = models.ForeignKey(Task, related_name='calculate_vectors', on_delete=models.CASCADE) method = models.CharField() vector = models.ForeignKey(Vector, models.SET_NULL, related_name='vector') so each CalculateVector instance has info about only one Vector model instance, but Vector model can contain several CalculateVector instances. and my serializers are: class VectorSerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = Vector fields = ( 'id', 'name' ) class CalculateVectorSerializer(serializers.ModelSerializer): vector = VectorSerializer() class Meta: model = CalculateVector fields = ( 'id', 'method', 'vector' ) class CreateTaskSerializer(serializers.ModelSerializer): calculate_vectors = CalculateVectorSerializer() class Meta: model = Task fields = ( 'id', 'name', 'description', 'calculate_vectors' ) def create(self, validated_data): calculate_vector_data = validated_data.pop('calculate_vectors') instance = Task.objects.create(**validated_data) vector = Vector.objects.get(id=calculate_vector_data.get('vector')['id']) CalculateVector.objects.update_or_create( task_id=instance, method=calculate_vector_data['method'], vector=vector, ) return instance when tried to query this serializer I received an error using: >>> data = {'name':'test task','description':'description','calculate_vectors':{'vector':{'id':1,'name':'calc1'},'method':'method1'}} >>> serializer = CreateTaskSerializer(data=data) >>> serializer.is_valid() >>> serializer.save() >>> serializer.data AttributeError: Got AttributeError when attempting to get a value for field `vector` on serializer `CalculateVectorSerializer`. The serializer … -
Django diffrenet results from AND operation and sequential filter
If I have models like this: class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class PersonSession(models.Model): start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True, blank=True) person = models.ForeignKey(Person, related_name='sessions') class Billing(models.Model): DEBT = 'DE' BALANCED = 'BA' CREDIT = 'CR' session = models.OneToOneField(PersonSession, blank=False, null=False, related_name='billing') STATUS = ((BALANCED, 'Balanced'), (DEBT, 'Debt'), (CREDIT, 'Credit')) status = models.CharField(max_length=2, choices=STATUS, blank=False, default=BALANCED ) The two below query generates different results: Person.objects.filter(Q(sessions__start_time__gte='2000-02-01') & \ Q(sessions__start_time__lte='2000-03-01') & \ Q(sessions__billing__status=Billing.DEBT)) OR Person.objects.filter(Q(sessions__start_time__gte='2000-02-01') & \ Q(sessions__start_time__lte='2000-03-01')).filter( Q(sessions__billing__status=Billing.DEBT)) The first one generates two person 1,2 and the second one generates all three persons that I have, the data is as below: id | first_name | last_name | id | start_time | end_time | person_id | id | status | session_id ---+------------+-----------+----+---------------------------+---------------------------+-----------+----+--------+------------ 0 | person | 0 | 0 | 2000-01-01 16:32:00+03:30 | 2000-01-01 17:32:00+03:30 | 0 | 0 | DE | 0 0 | person | 0 | 1 | 2000-02-01 16:32:00+03:30 | 2000-02-01 17:32:00+03:30 | 0 | 1 | BA | 1 0 | person | 0 | 2 | 2000-03-01 16:32:00+03:30 | 2000-03-01 17:32:00+03:30 | 0 | 2 | DE | 2 1 | person | 1 | 3 | 2000-01-01 16:32:00+03:30 | 2000-01-01 17:32:00+03:30 | 1 … -
Django: Security of post api without any authentication
I am creating api end points using django for my android mobile app. I have a signup POST api login POST api and notification token POST api All these views will not need any token based authentication. I am afraid someknow knows the api they can misuse them. How to protect them -
Can do with django migrate
hello, I have a problem with migration please help. what the problem (test_django) G:\test_django\courses_django>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, lesson_fifth, lesson_fouth, s essions Running migrations: Applying lesson_fifth.0002_article_author...Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "G:\test_django\lib\site-packages\django\core\management__init__.py", li ne 371, in execute_from_command_line utility.execute() File "G:\test_django\lib\site-packages\django\core\management__init__.py", li ne 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\test_django\lib\site-packages\django\core\management\base.py", line 2 88, in run_from_argv self.execute(*args, **cmd_options) File "G:\test_django\lib\site-packages\django\core\management\base.py", line 3 35, in execute output = self.handle(*args, **options) File "G:\test_django\lib\site-packages\django\core\management\commands\migrate .py", line 200, in handle fake_initial=fake_initial, File "G:\test_django\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_i nitial=fake_initial) File "G:\test_django\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_ initial) File "G:\test_django\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "G:\test_django\lib\site-packages\django\db\migrations\migration.py", lin e 122, in apply operation.database_forwards(self.app_label, schema_editor, old_state, projec t_state) File "G:\test_django\lib\site-packages\django\db\migrations\operations\fields. py", line 84, in database_forwards field, File "G:\test_django\lib\site-packages\django\db\backends\sqlite3\schema.py", line 306, in add_field self._remake_table(model, create_field=field) File "G:\test_django\lib\site-packages\django\db\backends\sqlite3\schema.py", line 178, in _remake_table self.effective_default(create_field) File "G:\test_django\lib\site-packages\django\db\backends\base\schema.py", lin e 224, in effective_default default = field.get_db_prep_save(default, self.connection) File "G:\test_django\lib\site-packages\django\db\models\fields\related.py", li ne 936, in get_db_prep_save return self.target_field.get_db_prep_save(value, connection=connection) File "G:\test_django\lib\site-packages\django\db\models\fields__init__.py", l ine 767, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "G:\test_django\lib\site-packages\django\db\models\fields__init__.py", l ine 939, in get_db_prep_value value = … -
Efficient way to scrape images from website in Django/Python
First I guess I should say I am still a bit of a Django/Python noob. I am in the midst of a project that allows users to enter a URL, the site scrapes the content from that page and returns images over a certain size and the page title tag so the user can then pick which image they want to use on their profile. A pretty standard scenario I assume. I have this working by using Selenium (headless Chrome browser) to grab the destination page content, some python to determine the file size and then my Django view spits it all out into a template. I then have it coded in such a way that the image the user selects will be downloaded and stored locally. However I seriously doubt the scalability of this, its currently just running locally and I am very concerned about how this would cope if there were lots of users all running at the same time. I am firing up that headless chrome browser every time a request is made which doesn't sound efficient, I am having to download the image to determine it's size so I can decide whether it's large enough. One … -
Generate thumbnail for inmemory uploaded video file
The client app uploaded a video file and i need to generate a thumbnail and dump it to AWS s3 and return the client the link to the thumbnail. I searched around and found ffmpeg fit for the purpose. The following was the code i could come up with: from ffmpy import FFmpeg import tempfile def generate_thumbnails(file_name): output_file = tempfile.NamedTemporaryFile(suffix='.jpg', delete=False, prefix=file_name) output_file_path = output_file.name try: # generate the thumbnail using the first frame of the video ff = FFmpeg(inputs={file_name: None}, outputs={output_file_path: ['-ss', '00:00:1', '-vframes', '1']}) ff.run() # upload generated thumbnail to s3 logic # return uploaded s3 path except: error = traceback.format_exc() write_error_log(error) finally: os.remove(output_file_path) return '' I was using django and was greeted with permission error for the above. I found out later than ffmpeg requires the file to be on the disk and doesn't just take into account the InMemory uploaded file (I may be wrong as i assumed this). Is there a way to read in memory video file likes normal ones using ffmpeg or should i use StringIO and dump it onto a temp. file? I prefer to not have the above done as it is an overhead. Any alternative solution with a better benchmark … -
No matching distribution found for django for python 3.6.5
I am building new Django app with a new version of Django. I found Django 2.0 is available (2.0.5) https://www.djangoproject.com/download/, and now trying to install it with pip. pip install Django==2.0.5 But it's not working for me. Collecting Django==2.0.5 Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/django/ Could not find a version that satisfies the requirement Django==2.0.5 (from versions: ) No matching distribution found for Django==2.0.5 I am using python 3.6.5 and pip 9.0.3. What's wrong here? -
django reusable app: remove dependencies in migrations?
I am writing a reusable django app, for django-cms. It will provide some cms-plugins, and a plugin framework. I have created migrations for my plugins. I started it some time ago, and the first plugins and it's migrations were created using django-cms==3.4.something, and they reference in there migrations files a dependency like this: dependencies = [ ('cms', '0016_auto_20160608_1535'), ] Now I worked again on that project, on another computer, installing django-cms==3.5.2 into my virtualenv. For a new plugin, this creates new migrations like this: dependencies = [ ('cms', '0020_old_tree_cleanup'), ] Obviously, this new migration cannot be used in an older cms project, using django-cms 3.4.x, as the needed dependency migration is not present. The question: Shall I add the 3.4.x migration dependency into my newly created migration? Or would it be better to completely remove those dependencies from my migrations (I doubt...)? -
How to modify my login to verify email?
I have already used login class class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) And views file of my app from .forms import LoginForm def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'],password=cd['password']) if user.is_active: login(request, user) return HttpResponse('Authenticated!') else: return HttpResponse('Disabled account') else: form = LoginForm() return render(request, 'account/login.html', {'form': form}) (hunter) provides email verifier.This is HTTP request example GET https://api.hunter.io/v2/email-verifier?email=steli@close.io How to modify my login and views files? -
JSON to POJO and/or POCO classes
I have a JSON as following: { "collaborators": [], "responsibilities": [ { "name": "Name" }, { "name": "Age" } ], "id": 12, "thing": "Reader" } My frontend is Angular and backend is Django. I am interested in converting this JSON into POJO and/or POCO classes. I see there are services online (http://json2csharp.com/) where one can paste JSON manually and get the POCO/POJO. I want to achieve this within my app. Is it convenient to do this on frontend side or backend side? Are there any libraries, APIs which could be of help? My quick google search wasn't much of a help. -
External file as Django File object
I have been trying to open external file (out of django's project root directory) and convert it to Django File object and then store to database, in FileField. I am receiving files through both GET and POST request. Files in POST request are passed as File Uploads, so they are directly received in django's internal directory, and can be converted to Django File object. But in case of GET, I just receive the file path: "/home/user/somefile.txt". File can be of any type, like text, image, csv, xls, etc. With python's file open, the file can be opened, even inside django, just the problem occurs when converting it to Django File, which says that the file is outside project root directory. I was thinking to open file, write it to internal directory with python basic file operation, then convert it to Django File object, but it may give encoding issues. There should be some better way than this. (Django v1.11, Python v3.6) -
Not saved checkbox-es to Django admin db
Django == 1.11 I have a simple models.py with task and label (it should be checkboxes that can be selected). class Task(models.Model): author = models.ForeignKey('auth.User', on_delete=models.PROTECT) name_task = models.CharField(max_length=1000) label_task = models.ManyToManyField(LabelTask) def __str__(self): return self.name_task and label class LabelTask(models.Model): name = models.CharField(max_length=1000) def __str__(self): return self.name forms.py look like class CreateTask(forms.ModelForm): label_task = forms.ModelMultipleChoiceField(queryset=LabelTask.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = Task exclude = ['author'] And my views.py @login_required def secret_page(request): form = CreateTask(request.POST or None) if form.is_valid(): print('Valid') instance = form.save(commit=False) instance.author = request.user instance.save() messages.success(request, "Successfully Created") else: print('Not valid') form = CreateTask() return render(request, 'task/task.html', {'form': form}) For example, go to a browser and type some data in the form - https://www.dropbox.com/s/rf7tbbvushln94d/Screenshot%20from%202018-05-09%2011-33-24.png?dl=0 And press submit. What do we see? https://www.dropbox.com/s/h27kdqddl1ns0r1/Screenshot%20from%202018-05-09%2011-33-56.png?dl=0 We chose only the Python, but in admin, we see the whole selection. I don't understand why is it so. Thank you. -
Django create custome admin view with non database fields
I would like to create a custome admin view with fields with data that I fill manually, meaning that there's no database table behind. In my admin.py I have this so far class TestAdmin(admin.ModelAdmin): pass admin.site.register(Test, TestAdmin) and in the models.py class Test(models.Model): test = models.BooleanField( default=True ) But with this I receive an error django.db.utils.ProgrammingError: relation "..._test" does not exist Django is looking up the table in the database but in my model I need only fields which data I fill manually -
Django unit testing: How should one test abstract models?
In my Django Project I have an app called 'core' which contains all my reusable model mixins / abstract models (behaviors.py), models (models.py), views (views.py) and helpers functions (utils.py): core/ __init__.py behaviors.py models.py utils.py views.py I know want to write tests for these files. For models, utils and views I just wrote unit tests like I'm used to. I'm now uncertain how I should test the abstract models contained in behaviors.py. For example I have this model mixin: import uuid as uuid_lib from django.db import models class UniversallyUniqueIdentifiable(models.Model): uuid = models.UUIDField( db_index=True, default=uuid_lib.uuid4, editable=False ) class Meta: abstract = True How can you test a abstract model? In one of the articles I used to learn about fat models, the author just tests the models in which he used the abstract models. But that feels not very DRY to me, since that would mean I would have to test the adding of the UUID in each model I use it in. Is there a better way to do it? -
django modelviewset Response add Other Information and when i request Post want not call create()
MyPostList.py class PostList(viewsets.ModelViewSet): queryset = Postinfo.objects.all().order_by('-postuid')[:10] serializer_class = PostListSerializer PostListSerializer.py class PostListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Postinfo fields = ("content", "useruid") models.py class Postinfo(models.Model): postuid = models.BigAutoField(db_column='WorryUID', primary_key=True) useruid = models.BigIntegerField(db_column='UserUID') content = models.TextField(db_column='Content') registerdate = models.DateTimeField( db_column='RegisterDate', default=datetime.datetime.today().strftime("%Y-%m-%dT%H:%M:%S")) class Meta: managed = False db_table = 'postinfo' i want response pagenumber if i request PostList i want response postlist and PageNo like this queryset = Postinfo.objects.all().order_by('-postuid')[:10] {"PostList":queryset, "PageNo":1} and i send pageNo = 2 queryset = Postinfo.objects.all().order_by('-postuid')[10:20] {"PostList":queryset, "PageNo":2} i have two problem first request(GET) succes PostList but can't add PageNo if i send PageNo it is not request(GET) this is POST so call create() -
How do I make a progress bar that reflects the process of importing a large csv file, using django?
How do I make a progress bar that reflects the process of importing a large csv file into a sqlite database? -
How to multiple sql query run in one products = cursor.fetchall() in django?
Here is my queries cursor.execute(""" Select id,reference_number, product_name from inventory_product where reference_number in('161633', '161627', '161629') group by id, reference_number, product_name """) products = cursor.fetchall() cursor.execute(""" Select SUM(quantity), product_id from inventory_productmovement where order_completed_date between'2017-07-01' AND '2018-03-25' AND status = 'CP' AND destination = 'SL' AND product_id in('905', '903', '901') group by quantity, product_id """) issue_to_shelf = cursor.fetchall() cursor.execute(""" Select SUM(opening_balance), product_id from inventory_itemopeningbalancerecord where date between'2017-07-01' AND '2018-03-25' AND product_id in('905', '903', '901') group by opening_balance, product_id """) start_balance = cursor.fetchall() I need all 3 quires in one products = cursor.fetchall(). becuase i need to write data on excel so i can run for loop easily. -
Unable to display data from model in template
I am trying to display data from a model inside my post.html which worked before but now dosen't for some reason I can't figure out. urls.py urlpatterns = [ path('', ListView.as_view( queryset=Tutorials.objects.all().order_by("-date")[:25], template_name="tutorials/blog.html" )), path('<int:pk>', DetailView.as_view( model=Tutorials, template_name="tutorials/post.html")), ] blog.html {% block python %} {% for Tutorials in object_list %} {% if Tutorials.categories == "pythonbasics" %} <a href="/tutorials/{{ Tutorials.id }}"><h1>{{ Tutorials.title }}</h1></a> <br> Created On : {{ Tutorials.date|date:"Y-m-d" }} {% endif %} {% endfor %} {% endblock %} post.html {% block content %} <h3>{{ Tutorials.title }}</h3> <h6> on {{ Tutorials.datetime }}</h6> <div class = "code"> {{ Tutorials.content|linebreaks }} </div> {% endblock %} -
enable gateway url for login django
I'm trying to figure out how can I open make a separate url and enable it as a gateway for login. The idea is that I'll send a generated url something like https://mywebpage/?token=12412414, you will click on it and you will login into the web app. The current setup allows me to create user over api, and I can obtain a token a for him using jwt rest framework which ideally I would send to you. Can someone help me understand how to do this, this is my first time handling this kind a request, thanks. -
How to ship migrations in a Django reusable app?
I can create migrations for my reusable application from a minimal test project, but that would install the migrations in - /usr/local/lib/python3.5/dist-packages/django_app-0.1-py3.5.egg/django_app/migrations/0001_initial.py I wanna ship the migrations with the reusable app, Do I just copy the file or is there any other method? -
Fatal error in launcher: Unable to create process using '"' when running django-admin.exe using python
i have my python installed in my desktop the version is python 3.6.4. Now i tried to create a Virtual environment: Windows using this command below C:\Users\YOUR Name\djangogirls1> python -m venv myvenv and this has been successfully created a myvenv folder inside djangogirls1 folder. Now i start to run my virtual environment by running: C:\Users\YOUR Name\djangogirls1> myvenv\Scripts\activate Now i tried to copy the Django-2.0.5 folder and files inside to folder djangogirls1 myvenv folder then tried to run the command like this (myvenv) C:\Users\YOUR Name\Documents\djangogirls1>python -m django --version 2.0.5 now my Django version is 2.0.5 and i think my django is successfully installed. Now my Python is located in: C:\Program Files\Python36 inside my C:\Program Files\Python36\Scripts i added two files which is django-admin.exe and django-admin.py when i tried to run this command Create project: Windows (myvenv) C:\Users\YOUR Name\Documents\djangogirls1>django-admin.exe startpoject mysite . i get this line of error Fatal error in launcher: Unable to create process using '"' My pip is also updated. I dont know why i get the error. Also in my environmental variables i added the path C:\Program Files\Python36\Scripts\;C:\Program Files\Python36\Scripts\django-admin.exe\ Can someone help me figured this thing out? Im stuck on this one. Any help is muchly Appreciated. TIA -
Not able to activate Conda Virtual Environment on Windows 8.1 machine
I have been working with Atom text editor, Anacond and Python for a project and I am able to activate the virtual environment, however, when I type in the command to activate the virtual environment, it does nothing. I have attached a screenshot. Attached is the CMD command screenshot However, when I run the command, conda info --envs I am able to view the environment. Please advise. Thanks in advance for help. -
how to update a website regularly with python program
Hi fellow scriptwriters, I have a python program that outputs data frequently but i would like to have this data displayed on a website automatically instead of manually doing so due to the large amount of data it is, so the question is how do i do this? I have been finding conflicting information online but most of it insists i have to use an online server, I'm looking for confirmation that that can work before diving into new territory, and if it does, can i connect the output from a server to automatically update a django webapp? Thanks, Massive Love -
Django-wkhtmltopdf returned non-zero exit status 1
I'm receiving the following error using wkhtmltopdf in a Django project in development. If I try and run it using an Apache server the status code returned is 6 rather than 1. Command '['wkhtmltopdf', '--disable-javascript', '--encoding', u'utf8', '--quiet', u'False', '/tmp/wkhtmltopdfnUwu3t.html', '-']' returned non-zero exit status 1 This is my view. class MyPDF(OrgOwnerMixin, PDFTemplateView): filename = 'my_pdf.pdf' template_name = 'pdf/test.html' def get_object(self, *args, **kwargs): return Organisation.objects.get(slug=self.kwargs['slug']) def get_context_data(self, *args, **kwargs): ctx = super(MyPDF, self).get_context_data(*args, **kwargs) ctx['object'] = self.get_object() return ctx And here is the Traceback: Traceback: File "/home/henry/Documents/Sites/Development/fargus/env/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/henry/Documents/Sites/Development/fargus/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "/home/henry/Documents/Sites/Development/fargus/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 215. response = response.render() File "/home/henry/Documents/Sites/Development/fargus/env/local/lib/python2.7/site-packages/django/template/response.py" in render 107. self.content = self.rendered_content File "/home/henry/Documents/Sites/Development/fargus/env/local/lib/python2.7/site-packages/wkhtmltopdf/views.py" in rendered_content 78. cmd_options=cmd_options File "/home/henry/Documents/Sites/Development/fargus/env/local/lib/python2.7/site-packages/wkhtmltopdf/utils.py" in render_pdf_from_template 186. cmd_options=cmd_options) File "/home/henry/Documents/Sites/Development/fargus/env/local/lib/python2.7/site-packages/wkhtmltopdf/utils.py" in convert_to_pdf 124. return wkhtmltopdf(pages=filename, **cmd_options) File "/home/henry/Documents/Sites/Development/fargus/env/local/lib/python2.7/site-packages/wkhtmltopdf/utils.py" in wkhtmltopdf 110. return check_output(ck_args, **ck_kwargs) File "/usr/lib/python2.7/subprocess.py" in check_output 574. raise CalledProcessError(retcode, cmd, output=output) Exception Type: CalledProcessError at /pdf/org-1/ Exception Value: Command '['wkhtmltopdf', '--disable-javascript', '--encoding', u'utf8', '--quiet', u'False', '/tmp/wkhtmltopdfEG5K8j.html', '-']' returned non-zero exit status 1 Any help will be much appreciated -
Sending Email With Celery Using Django Default Email Backend
I am trying to send confirmation email to my registered user using Django and Celery. I am using RabbitMQ as the Broker. Whenever I'm executing the code, the celery log shows it is receiving the task and executing successfully, But I am not receiving any emails. tasks.py from celery.task import Task from django.core.mail import send_mail from django.template import loader from django.utils.html import strip_tags from config.celery import app from config.settings import default class SendConfirmationEmail(Task): def __init__(self, *args, **kwargs): self.user_name = kwargs.get('username') self.user_id = kwargs.get('id') self.user_hash = kwargs.get('hash') self.user_email = kwargs.get('email') def send_email(self): confirm_mail = loader.render_to_string('mail/confirmation.html', {'user': self.user_name, 'id': self.user_id, 'hash': self.user_hash, 'domain': default.SITE_URL}) text_email = strip_tags(confirm_mail) send_mail( subject='Confirm Your E-mail', message=text_email, from_email='no-reply@mysite.com', recipient_list=[self.user_email], fail_silently=False, html_message=confirm_mail ) def run(self, *args, **kwargs): self.send_email() app.register_task(SendConfirmationEmail()) signals.py from django.db.models.signals import post_save from django.dispatch import receiver from apps.siteuser.models import User from apps.siteuser.tasks import SendConfirmationEmail @receiver(post_save, sender=User) def create_employee_details(sender, instance, created, **kwargs): if created: task = SendConfirmationEmail(username=instance.first_name, id=instance.id, hash=instance.hash, email=instance.email) task.delay() settings for Email & Celery: CELERY_BROKER_URL = 'amqp://username:password@localhost:5672/vhost' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.mailtrap.io' EMAIL_HOST_USER = MY_USERNAME EMAIL_HOST_PASSWORD = MY_PASSWORD EMAIL_PORT = 2525 Celery log: [2018-05-09 11:50:41,191: INFO/MainProcess] Received task: apps.user.tasks.SendConfirmationEmail[e63c0f5f-7b81-4065-85c1-9ef87acc792a] [2018-05-09 11:50:41,197: INFO/ForkPoolWorker-1] Task apps.user.tasks.SendConfirmationEmail[e63c0f5f-7b81-4065-85c1-9ef87acc792a] succeeded in 0.004487647999667388s: None NOTE: I have sent mail without …