Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to exclude 'queryset' characters when using django sqlite orm
I want to send mail to many users using django sendmail. I am using orm in sqlite3 to get the list of recipients stored in db. However, the orm result includes 'queryset', so mail cannot be sent Is there a way to exclude 'queryset' from orm results? as-is I want views.py def send_form(request): if request.method == 'POST': selected_target = request.POST['target'] target = contact.objects.filter(target=selected_target).values_list('email') return render(request, 'view/send_form.html', {'target': target}) def send_success(request): if request.method == 'POST': subject = request.POST['subject'] recipient = request.POST['email'] message = request.POST['message'] send_mail( subject, message, recipient, [recipient], fail_silently=False, ) return render(request, 'view/send_success.html') send result -
How can I make my Django API only accept requests that come from my website itself?
I had to create an API for my Django application for something sensitive that I couldn't have in a public and static Javascript file. How can I make it so that this view only accepts requests coming from my own website, and reject any from the "outside" (if someone copied my request below they should get an error)? If there are any other security concerns please do mention them in your response. My website is hosted on Heroku. The request in my javascript file: var clientSecret = await fetch('https://url.com/api/', { method: 'POST', body: params, headers: { 'Content-Type': 'text/plain' }, }).then(r => r.json()) My view for my API (https://url.com/api/): @api_view(['POST']) def payment(request, *args, **kwargs): ... #define headers_in and params_in here response = requests.post('https://outboundapirequest.com/v1/request', headers=headers_in, data=params_in) return Response(response.json()['value']) -
Django create auto profile?
from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Why use instance.profile.save() again? Profile.objects.create(user=instance) isn't enough??? -
Cant save datetime in django ajax call
I have a Profile model assigned to a user which contains the field : consent = models.DateTimeField(default=timezone.now, blank=True, null=True) I have created a switch in frontend in which the user gives consent for data tracking or no and and ajax call for handling the response. It seems to work fine , it is printing the correct outputs but the datetime does not save in the database. Any idea what is wrong? def user_consent(request): edited_user = request.user # if no user is specified, then we take the signed in user if request.is_ajax and request.method == "GET" : value = request.GET['toggle'] print(value) if value == 'true': edited_user.profile.consent = timezone.now() edited_user.save() print(edited_user.profile.consent) return JsonResponse({"ok": "no errors"}, status=200) else: edited_user.profile.consent = None edited_user.save() print(edited_user.profile.consent) return JsonResponse({"ok": "no errors"}, status=200) return JsonResponse({"error": "there was an error"}, status=400) The outputs im getting in console : [01/Jul/2022 14:53:50] "GET /users/consent?toggle=false HTTP/1.1" 200 19 true 2022-07-01 14:53:51.911242+00:00 [01/Jul/2022 14:53:51] "GET /users/consent?toggle=true HTTP/1.1" 200 19 false None [01/Jul/2022 14:53:53] "GET /users/consent?toggle=false HTTP/1.1" 200 19 true 2022-07-01 14:53:55.522132+00:00 [01/Jul/2022 14:53:55] "GET /users/consent?toggle=true HTTP/1.1" 200 19 false None [01/Jul/2022 14:55:08] "GET /users/consent?toggle=false HTTP/1.1" 200 19 -
Querying null in JSONField is different between Django 3.2 and 4.0
Let's say I have a Django model with a JSONField: class Event(models.Model): data = models.JSONField() And I create the following objects: event1 = Event.objects.create(data={"key": None}) event2 = Event.objects.create(data={"key": "null"}) In Django 3.2.13, the following queries return some results: Event.objects.filter(data__key=Value("null")) # [event1] Event.objects.filter(data__key="null") # [event2] In Django 4.0.5, the same queries return different results: Event.objects.filter(data__key=Value("null")) # [event1, event2] Event.objects.filter(data__key="null") # [event1, event2] The Django docs aren't clear which results are correct. I would lean towards the v3 results. Any idea which one is correct? Is this a bug in v4? I filed a ticket in the Django bug tracker here: https://code.djangoproject.com/ticket/33820#ticket -
How to get the FileField from ModelFrom in django views
I currently want to send some data to my database by doing the following: Sending a document to the database and each document has a foreign key from the user table i.e. each document is a reference to an author(from another table) but it will be bad for the user to get all the users in the system and choosing one of them, I want the author assignment to be performed in the views. So as a summary I want to get fields from the form in views. I found a corresponding question and tip at this link, but the only issue here being that a file was not inlcuded in his model but on mine yes. Snipets of my files below; models.py class UploadedDocuments(models.Model): user = models.ForeignKey( TheUsers, on_delete=models.CASCADE, ) document = models.FileField( verbose_name='Document', upload_to=f'documents/%Y/', null=True, ) plagiarism_status = models.CharField(max_length=100, null=True) serialised_content = models.CharField(null=True, max_length=255) date_uploaded = models.DateTimeField( verbose_name='Uploaded On', auto_now_add=True ) def __str__(self): return self.document.name class Meta: verbose_name = "Document" verbose_name_plural = 'Documents' Views.py def upload(request): form = UploadedDocumentsForm(request.POST, request.FILES) if request.POST: if form.is_valid(): form_stack = form.save(commit = False) form.user = request.user form_stack.serialised_content = "bala" form_stack.plagiarism_status = 'Hello' form_stack.save() return redirect("results") function which is constantly telling me invalid. … -
The checkout. Isn't working so the orders doesn't show in the admin order page
My checkout isn't working so the orders aren't showing at the Canteen order So I don't know why the checkout isn't working I redirected to the success page and it's giving me error I need help It is urgent for a project Here is my github https://github.com/abuhviktor/Finalyearproject/tree/main I know the code isn't dynamic but I am trying to be better everyday I didn't paste the code cause it's alot So any part u need I will paste it -
How to access Django request body from Javascript?
I'm making the following request in JS to my Django API endpoint. params = {"amount": String(amount), "currency": "usd", "description": "label"}; console.log(params) var clientSecret = await fetch('https://url.com/api/payment/', { method: 'POST', body: params, headers: { 'Content-Type': 'application/json' }, }).then(r => r.json()) Here's the view def payment(request, *args, **kwargs): print("here") body = request.POST.copy() print("present") print(body) print(type(body)) print(list(body)) headers_in = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer key', } response = requests.post('https://api.stripe.com/v1/payment_intents', headers=headers_in, data=params_in) return Response(response.json()['client_secret']) body = request.POST.copy() is giving me a Bad Request: /api/payment/ bad request in my logs -
Django template tag show value not key
This is probably a simple answer, but I can't seem to find it in the docs. How do I display the value of a choice field in template tags? Using .value did not work as I thought it may. Right now it's just displaying the Key: user_update when I call this template tag on my html: {{ ticket.current_status }} from my forms.py: current_status = ChoiceField( label = "", choices = STATUS_CHOICES, widget = Select(attrs={ 'class': 'h-10 flex flex-row justify-items-left', }) ) and my views.py: class StaffSupportTicketUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): ... def get_context_data(self, **kwargs): context = super(StaffSupportTicketUpdateView, self).get_context_data(**kwargs) context['search'] = SearchForm() context['ticket'] = self.get_object() return context and my models.py: class SupportTicketModel(Model): ... current_status = CharField(default='new_ticket', choices=STATUS_CHOICES, max_length=35) ... finally, my STATUS_CHOICES STATUS_CHOICES = ( ('new_ticket', 'New ticket submitted'), ('user_update', 'User updated ticket'), ('need_info', "Need more information"), ('completed', 'Completed'), ) -
Getting UnicodeDecodeError when converting a InMemoryUploadedFile to Google MediaUpload
I am looking for your assistance with the following situation: I am building a Django Application and I am orchestrating the instance on Google App Engine, Once your Google App Engine instance it's running it will enter into a "readonly" mode, and therefore Django can no longer write files into the "disk space" With this mind, The Django application is receiving a 'File' submitted through a form, per Django documentation File Uploads are considered an UploadedFile Instance which is then becomes a subclass of InMemoryUploadedFile, If I attempt to pass this object to MediaUpload class I got the following message: (<class 'TypeError'>, TypeError('expected str, bytes or os.PathLike object, not InMemoryUploadedFile'), <traceback object at 0x0000014D00669900>) I need to convert this object to a bytes object as my end goal is to Upload this file into Google Drive using Google APIs I tried to read the object (assuming the 'read' method will return the rawdata (bytes)) but I am getting a Decode error when I do that. Uploading a File to Google Drive is described in their documentation but it seems the MediaFileUpload Class only accepts Strings/Paths unclear if accepts bytes. Looking at the error message I got "(<class 'UnicodeDecodeError'>, UnicodeDecodeError...." Image … -
My Checkout isn't working and so the orders aren't showing in the canteen order
My checkout isn't working so the orders aren't showing at the Canteen order So I don't know why the checkout isn't working I redirected to the success page and it's giving me error I need help It is urgent for a project Here is my github https://github.com/abuhviktor/Finalyearproject/tree/main I know the code isn't dynamic but I am trying to be better everyday I didn't paste the code cause it's alot So any part u need I will paste it -
Popup selected items from the form from python Django
I need to show the selected value from one page to another page, which means while I'm going to update my question I need to show the corresponding field to that form. Now I'm selecting the value using a drop-down list instead of that I need to the popup that value. Django form.py class QuestionForm(forms.ModelForm): #this will show dropdown __str__ method course model is shown on html so override it #to_field_name this will fetch corresponding value user_id present in course model and return it courseID=forms.ModelChoiceField(queryset=models.Course.objects.all(), to_field_name="id") This is my views.py def update_question_view(request,pk): question=QModel.Question.objects.get(id=pk) #course=QModel.Question.objects.get(id=question.course_id) questionForm=forms.QuestionForm(instance=question) #CourseForm=forms.CourseForm(instance=course) mydict={'questionForm':questionForm} if request.method=='POST': questionForm=forms.QuestionForm(request.POST,instance=question) if questionForm.is_valid(): question=questionForm.save(commit=False) course=models.Course.objects.get(id=request.POST.get('courseID')) question.course=course question.save() else: print("form is invalid") return HttpResponseRedirect('/admin-view-question') return render(request,'exam/update_question.html',context=mydict) This is my models.py class Course(models.Model): course_name = models.CharField(max_length=50) question_number = models.PositiveIntegerField() def __str__(self): return self.course_name class Question(models.Model): course=models.ForeignKey(Course,on_delete=models.CASCADE) question=models.CharField(max_length=600) option1=models.CharField(max_length=200) option2=models.CharField(max_length=200) option3=models.CharField(max_length=200) option4=models.CharField(max_length=200) status= models.BooleanField(default=False) cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4')) answer=models.CharField(max_length=200,choices=cat) This is the template: [![form method="POST" autocomplete="off" style="margin:100px;margin-top: 0px;"> {%csrf_token%} <div class="form-group"> <label for="question">Skill Set</label> {% render_field questionForm.courseID|attr:'required:true' class="form-control" %} <br> <label for="question">Question</label> {% render_field questionForm.question|attr:'required:true' class="form-control" placeholder="Example: Which one of the following is not a phase of Prototyping Model?" %} <br> <label for="option1">Option 1</label> {% render_field questionForm.option1|attr:'required:true' class="form-control" placeholder="Example: Quick Design" %} <br> <label for="option2">Option 2</label> {% … -
Using static image for inline css background
I'm attempting to use a static image as an inline background-image declaration within my html. <div class="billboard" style="background-image: url('/static/images/friends.jpg');"> This renders ok in my local env, but not in production. I've seen people indicate that the use if {{STATIC_URL}} could be used, but this doesn't seem to work locally. Might work in prod. Any advice would be great. Thanks! -
Djando, two models inherited from the same parent, one of them has a ForienKey to the other
I created two models inherited from the same parent. In one of them, I am trying to make a ForienKey to the other child. The following error appears TypeError: ForeignKey(<django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor object at 0x7f2cdf0af9d0>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' user_model.py class AppUser(AbstractBaseUser, PermissionsMixin): objects = MyUserManager() username = models.CharField(max_length=128) email = models.EmailField(max_length=64, unique=True) . . class SupervisorUser(AppUser): objects = StudentManager() major = models.CharField(max_length=128) . . class StudentUser(AppUser): objects = StudentManager() GPA = models.DecimalField(max_digits=4,decimal_places=2) supervisor = models.ForeignKey(SupervisorUser, on_delete=models.CASCADE) . . I tried supervisor = models.ForeignKey(AppUser.SupervisorUser, on_delete=models.CASCADE) but the following error appeared AttributeError: type object 'AppUser' has no attribute 'SupervisorUser' -
How can i write a reverse url for a bridge table in django admin?
model.py class Project(models.Model): project_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) winners = models.ManyToManyField('TwitterUser', blank=True, symmetrical=False, related_name='winners') class TwitterUser(models.Model): projects = models.ManyToManyField(Project, blank=True, symmetrical=False, related_name='registered') This url worked for getting users that registered for a project admin.py url = ( reverse("admin:mint_twitteruser_changelist") + "?" + urlencode({"projects__project_id": f"{obj.project_id}"}) ) How do i get url to display the winners in the admin page -
Web Scraping with python I can't print my variable
In my Django project I use BeautifulSoup for web scraping.It works ut I can't print or slice it. When I try it give the error: (I'm doing this on the views.py) "UnicodeEncodeError 'charmap' codec can't encode character '\u200e' in position 59: character maps to <undefined " . How can I print x variable? URL = link user_agent = getRandomUserAgent() headers = {"User-Agent": user_agent} page = requests.get(URL, headers=headers) soup = BeautifulSoup(page.content, 'html.parser') list = soup.find_all("td", class_="a-size-base prodDetAttrValue") for x in list: print(x) -
How to set imagefield in django model with dynamically set sub directories
I need to upload photos to specific directories. I have below model code. @reversion.register() class Student(BaseModel): uuid = models.UUIDField(default=uuid.uuid4, verbose_name=_("Unique Identifier"), unique=True) user = models.OneToOneField(User, on_delete=models.PROTECT, db_index=True, verbose_name=_("User")) photo = models.ImageField(upload_to="student/", null=True, blank=True, verbose_name=_("Photo")) std_status = models.IntegerField(choices=STD_STATUS, default=1, verbose_name=_("Stu Sta")) std_no = models.AutoField(primary_key=True, verbose_name=_("Stu Num")) name = models.CharField(max_length=100, db_index=True, verbose_name=_("Name")) surname = models.CharField(max_length=100, db_index=True, verbose_name=_("Surname")) For the photo line. It uploads photos to student/ directory. But i need to have subdirectories with User name and dates. Like "student/jenifer_argon/2022/07/01" I can set "student/" directory but username and date should be dynamically set. How can i do this? -
Django (proxy and abstract) add extra fields to child of a custom-user class (AbstrsactBaseUser)
I created a custom user class that is inherited from AbstractBaseUser, this class has a chil class. The problem is I can't add new fields to the children's classes because they had (class Meta: proxy = Ture). The following error appears: ?: (models.E017) Proxy model 'StudentUser' contains model fields. user_model.py class AppUser(AbstractBaseUser, PermissionsMixin): objects = MyUserManager() username = models.CharField(max_length=128) email = models.EmailField(max_length=64, unique=True) . . . class StudentUser(AppUser): objects = StudentManager() GPA = models.DecimalField(max_digits=4,decimal_places=2) #This causes the error if proxy=True class Meta: proxy = True def save(self, *args, **kwargs): self.password = make_password(self.password) return super().save(*args, **kwargs) sittings.py AUTH_USER_MODEL = "app.AppUser admin.py admin.site.register(AppUser) admin.site.register(StudentUser) When I remove (proxy = True) from the child and add (abstract = True) to the parent the following error appears: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app.AppUser' that has not been installed user_model.py class AppUser(AbstractBaseUser, PermissionsMixin): objects = MyUserManager() class Meta: abstract = True username = models.CharField(max_length=128) email = models.EmailField(max_length=64, unique=True) . . . class StudentUser(AppUser): objects = StudentManager() GPA = models.DecimalField(max_digits=4,decimal_places=2) def save(self, *args, **kwargs): self.password = make_password(self.password) return super().save(*args, **kwargs) -
@xframe_options_exempt not working for Django view/template that displays an iFrame?
I am displaying an iFrame on my template, the contents of which is from a local .html that I have uploaded as a media file. I have X_FRAME_OPTIONS = 'SAMEORIGIN' set in my settings to allow the displaying of the contents, however when I run the --check deploy check, I get this message: WARNINGS: ?: (security.W019) You have 'django.middleware.clickjacking.XFrameOptionsMiddleware' in your MIDDLEWARE, but X_FRAME_OPTIONS is not set to 'DENY'. Unless there is a good reason for your site to serve other parts of itself in a frame, you should change it to 'DENY'. Seems like I should be keeping this set to DENY when I go to production, however by doing that, my iFrame is "unable to connect" to display the content. I've read the documentation here that says you can set exemptions on the view level if you set it to DENY, however it's not working for me. On the view function, I've tried using the decorators @xframe_options_sameorigin and @xframe_options_exempt like: # @xframe_options_sameorigin # Doesn't work # @xframe_options_exempt # Also doesn't work # Setting X_FRAME_OPTIONS = 'SAMEORIGIN' # and use @xframe_options_deny also doesn't work def work_detail(request, pk): work = Work.objects.get(pk=pk) context = { 'work': work } return render(request, 'work_detail.html', … -
Django Form, form is not being submitted
I am pretty new to django and I am having some issues with my form. It is not submitting anything. I don´t have any idea why, no issue appears in the terminal. It displays the form correctly, but when filling it out and submitting, it just redirects me to the same form but blank. I check the database and nothing´s been added. My code below: #views.py def ContractView(request): form=contractsform(request.POST) if form.is_valid(): con =form.save() return redirect("{% url 'contracts' %}", con.id) else: form = contractsform() return render(request, 'contform.html', {'form': form}) #contform.html <div class="card-body"> <form action="" method="POST" class="row g-3"> {% csrf_token %} <label for="{{ form.subject.id_for_label }}">Name:</label> {{form.name}} <div class="col-md-6"> <label for="{{ form.subject.id_for_label }}">Contractor:</label> <div class="input-group input-group-sm mb-3"> {{form.contractor}} <button id="new-vendor" class="btn btn-outline-secondary" type="button">+</button> </div> </div> <div class="col-md-6"> <label for="{{ form.subject.id_for_label }}">Contractee:</label> {{form.contractee}} </div> ... <div class="col-md-6"> <button type="button" onclick="javascript:history.back()">Cancel</button> </div> <div class="col-md-6"> <input type="submit" value="Submit" class="btn btn-primary" style="float: right;"> </div> </form> #forms.py class contractsform(forms.ModelForm): class Meta: model = Contratos fields = '__all__' widgets = { 'name': forms.TextInput(attrs ={'class': 'form-control'}), 'contractee': forms.TextInput(attrs={'class': 'form-control'}), 'contractor': forms.Select(attrs={'class': 'form-control', 'id': 'contractor_view' }),} #urls.py urlpatterns = [ path('contracts/', views.contratostabla, name='contracts'), path('contracts/add/', ContractView, name='new-contract'), ] -
Django Treebeard - showing hierarchy in admin page
I've used Django.treebeard to create a hierarchical system to classify books like so: The 'genres' model is related to another model by a many-to-many relationship, and I need to be able to select the right genres (ie, Fiction>Adult>Science Fiction>Hard Science Fiction) in the admin page for the other model. Checkboxes seem to be the best way to do this, but when I use them in they look like this: So I can't see the different levels of the hierarchy. The best I've been able to come up with is adding the following to the Models: def __str__(self): return '%s%s' % ('--' * self.depth, self.name) Which results in this, which is not much better: What I need is for the checkboxes themselves to move, not just the text, and to have functionality like being able to 'open' and 'shut' the parent categories, select/deselect all children by selecting the parent etc. Is there any way to do this? -
How to keep html form data after submission using django?
I created a form in html that returns data to Django each time it is submitted. However, when the page is reloaded after submission, the data entered in the form is lost. In order to solve this problem, I took inspiration from the documentation and this blog and then I modified my views.py file: def search(request): if request.method == 'POST': search = request.POST['search'] form = MyForm(request.POST) max_pages_to_scrap = 15 final_result = [] for page_num in range(1, max_pages_to_scrap+1): url = "https://www.ask.com/web?q=" + search + "&qo=pagination&page=" + str(page_num) res = requests.get(url) soup = bs(res.text, 'lxml') result_listings = soup.find_all('div', {'class': 'PartialSearchResults-item'}) for result in result_listings: result_title = result.find(class_='PartialSearchResults-item-title').text result_url = result.find('a').get('href') result_desc = result.find(class_='PartialSearchResults-item-abstract').text final_result.append((result_title, result_url, result_desc)) context = {'final_result': final_result} form = MyForm() return render(request, 'index.html', context,{'form':form}) I wrote the following code in my models.py file: from django import forms from django.db import models # Create your models here. class MyForm(forms.Form): search = forms.CharField(max_length=500) here is the content of my index.html file: <form method="POST" action="search"> {% csrf_token %} <input type="search" name="search" placeholder="Search here..." value="{{form.search.value}}" autofocus x-webkit-speech/> </form> Despite my modifications, the form data is not kept after submission. -
Use function from another file in Django views.py
I've created a whole function in my Django views.py and it works. It looks like this: SOME IMPORTS def get_campaigns(request): SOME CODE campaign_data = [] for batch in stream: for row in batch.results: data = {} data["campaign_id"] = row.campaign.id data["campaign_name"] = row.campaign.name campaign_data.append(data) return render(request, 'hello/get.html',{ 'data' : data }) But then I learned that having your whole functions on views.py is not a good practice at all. I should move the "big" functions to a different file and then call them on views.py, right? So I tried different options and the only one that worked for me is copying exactly that same code on a different file and then adding to my views.py: def index(request): data = get_campaigns(request), return render(request, 'index.html',{ 'data' : data }) So I'm repeating the same line (return render...) in both files. It works, but looks very ugly and maybe it's slow, buggy or even insecure. Is there a better solution? P.D: As you can guess from my question, I'm a complete beginner and I don't really know what I'm doing, so any pointers to beginner-friendly tutorials related to this are much appreciated. 😅 -
Django: mixing models and modelForms in same row of a table
I'm building a tournament organizing tool and I'm trying to display the scheduled matches in a table where each row represents a match, and the columns are player1, player1score, player2, player2score, player3, player3score, and "Submit Match Result". So the way I would like it is that the player1, player2, and player3 entries in the table are the names of the 3 players in the match (which is already determined previously when the match was scheduled) while I want the 3 score fields to be input fields. This way, the user puts in the three scores of the players and clicks "submit" which should then update the match in the database, changing it from "scheduled" to "finished" and recording the three scores. What I am having an issue with is how to do this mix of data from the Match model and from the MatchForm modelForm. My Match class: class Match(models.Model): status = models.CharField(max_length=256, default='Scheduled') player1 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name = 'player1') player2 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name = 'player2') player3 = models.ForeignKey(Player, on_delete=models.CASCADE, related_name = 'player3') player1score = models.IntegerField(default=0) player2score = models.IntegerField(default=0) player3score = models.IntegerField(default=0) And my MatchForm: class MatchForm(forms.ModelForm): class Meta(): model = Match fields = ('player1score', 'player2score', 'player3score') And … -
Django + Celery logging
There are alot of resources on this topic but none of them worked unfortunately. Here is my django setting for logging: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "default": { "format": "[%(asctime)s: %(levelname)s/%(processName)s] [%(name)s] %(message)s" } }, "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}}, "handlers": { "console": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "default", }, "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", }, "my_custom_handler": { "level": "INFO", "class": "my_custom_handler_class", }, }, "loggers": { "django.request": { "handlers": ["mail_admins"], "level": "ERROR", "propagate": True, }, "": { "handlers": ["console", "my_custom_handler"], "level": "INFO", "propagate": True, "formatter": "default", }, "celery": { "handlers": ["console", "my_custom_handler"], "level": "INFO", "propagate": True, }, }, } Celery is initialized before base.py is imported/settings are initialized (which may be the culprit) I tried setting CELERYD_HIJACK_ROOT_LOGGER = False, use the after_setup_task_logger signal (I tried printing to see if that signal is dispatched at all but it isn't) and none of them had any effect I tried using setup_logging which kind of worked: def config_loggers(*args, **kwags): my_handler = MyCustomHandler() root_logger = logging.getLogger() root_logger.addHandler(my_handler) root_logger.level = logging.INFO``` and then in: @worker_process_init.connect def init_worker(**kwargs): logger = get_task_logger(__name__) # or Logger.get_logger(__name__), no difference logger.info("My log message") and I say it kind of worked only because when …