Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter column with OR statement
I found a question very similar to this one but that one did not specify how to return a specific column and I have been trying combinations for the past few hours with no luck. home_team_list2 = PreviousLossesNbav1WithDateAgg.objects.values_list('actual_over_under_result_field', flat=True).filter(Q(away_team_field="Chicago") | Q(home_team_field="Chicago")) This does not throw me any errors but it does not return anything. I am attempting to return that specific column from my models filtering on away team or home team equal to "Chicago" -
Django form_valid() doesnt work for registration
I'm Try to create Registration Form With Django. But When i try, Form Doesn't Work, The Data not send to Database. I Know Why the form can't work, because method form_valid is not working. My Question Is How do i know it's not working ? Where i found the error ?. This is my code. models.py class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) full_name = models.CharField(max_length=150) create_account = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_reviewer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] def __str__(self): return self.full_name forms.py class RegistrationForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['full_name'].widget.attrs.update({ 'required' : '', 'type' : 'email', 'placeholder' : 'Nama Lengkap Anda', }) self.fields['email'].widget.attrs.update({ 'required' : '', 'type' : 'text', 'placeholder' : 'emailanda@universitasmulia.ac.id', }) self.fields['password1'].widget.attrs.update({ 'required' : '', 'type' : 'password', 'placeholder' : 'Password', }) self.fields['password2'].widget.attrs.update({ 'required' : '', 'type' : 'password', 'placeholder' : 'Konfirmasi Ulang Password', }) class Meta: model = Account fields = ("full_name", "email", "password1", "password2") views.py class RegistrationView(FormView): template_name = 'authentication/registration.html' form_class = RegistrationForm success_url = '/authentication' def form_valid(self, form): messages.success(self.request, 'Please Check Your Email For Infomation Detail!') print('Success Created Your Account') registration.html <form method="POST" class="register-form" id="register-form"> {% csrf_token %} <div class="form-group"> … -
What should i learn and how?
I want to become full stack developer and i want to learn HTML, CSS, JS and DJANGO(Python). which one i have to learn first and give how much time to each language. HTML CSS JS DJANGO -
Django ModuleNotFoundError: No module named 'my_app_name' while loading WSGI on ElasticBeanstalk
I'm trying to deploy my Django app to ElasticBeanstalk. I deployed my app without errors but when I access the root page it show 502 error and the log shows ModuleNotFoundError: No module named 'my_app_name' How can I solve this? Logs Dec 16 01:16:26 ip-172-31-43-109 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp Dec 16 01:16:26 ip-172-31-43-109 web: return util.import_app(self.app_uri) Dec 16 01:16:26 ip-172-31-43-109 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/util.py", line 359, in import_app Dec 16 01:16:26 ip-172-31-43-109 web: mod = importlib.import_module(module) Dec 16 01:16:26 ip-172-31-43-109 web: File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module Dec 16 01:16:26 ip-172-31-43-109 web: return _bootstrap._gcd_import(name[level:], package, level) Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap>", line 983, in _find_and_load Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap>", line 677, in _load_unlocked Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap_external>", line 728, in exec_module Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed Dec 16 01:16:26 ip-172-31-43-109 web: File "/var/app/current/src/my_app_name/wsgi.py", line 18, in <module> Dec 16 01:16:26 ip-172-31-43-109 web: application = get_wsgi_application() Dec 16 01:16:26 ip-172-31-43-109 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application … -
500 error on one specific page. Apache2. Ubuntu 18
As a developer, I have to let you know that I'm a great fan of Stackoverflow. I have solved so many problems thanks to all of you! Currently, I'm struggling with a 500 error. I have been looking for a solution through this page and the web, but I haven't found anything. I recently created a web app using tesseract to extract text from images. I successfully deployed the website using Ubuntu 18 and Django. The thing is that when I installed Apache2 to use it as an HTTP server the page that loads the images and converts them to text sent me a 500 error. The access logs are: [17/Dec/2021:01:48:59 +0000] "GET /main-app/downloads/ HTTP/1.1" 500 417 [17/Dec/2021:01:49:03 +0000] "GET /main-app/downloads/ HTTP/1.1" 500 417 The error logs are: [wsgi:error] [pid 755:tid 139986828527360] [wsgi:error] [pid 755:tid 139986761361152] in regards to how the page handles the request: file_path =os.path.join(BASE_DIR, file_url) str(file_path) if os.path.exists(file_path): path = open(file_path, 'r') mime_type, _ = mimetypes.guess_type(file_path) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) # Just in case: "attachment; filename=%s" % '.csv' return response else: raise Http404 Just to let you know, I have granted 775 permissions to the folders that handle the app and … -
Assigning value to variable inside for loop
I have a for loop that goes through a list of cities as well as their broad variables (safety, affordability, transit, etc). If there's a match between the city's broad&specific variable and the broad&specific variable the user selects on the page then it assigns a weighted value else the value is 0. I am trying to add the values for each broad variable in the list but I get the error local variable 'city_variable1_value' referenced before assignment When I reference city_variable1_value and city_variable2_value as 0 before the first if statement then my total_city_value = city_variable1_value + city_variable2_value equals 0 when it should be 0.24 for example. The code is below! # list of each variable's broad category broad_variable_list = ["safety", "affordability", "transit", "language", "attractions"] # weighting of each variable ranking weight_variable1 = 0.33 weight_variable2 = 0.24 weight_variable3 = 0.17 weight_variable4 = 0.14 weight_variable5 = 0.12 def get_ranking(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = RankingForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required specific_variable1 = form.cleaned_data['specific_variable1'] specific_variable2 … -
Errors in rendering booklist to templates
from django.http import HttpResponse booksList = [ { 'id' = '1', 'title' = "Beginner's Course in Django", 'description' = 'Foundational Course in Django'} { 'id' = '2', 'title' = "Intermediate Course in Django", 'description' = 'Next steps in Django' }, { 'id' = '3', 'title' = "Advanced Course in Django", 'description' = 'The complexities of Django' }, ] I am I am rendering data to a template using the above bookList and getting two errors: '[' was not closed Pylance and '{' was not closed Pylance Kindly advise. -
Django Forms, Class LoginForm(User): str() argument 'encoding' must be str, not tuple
I Got Error, class LoginForm(User): TypeError: str() argument 'encoding' must be str, not tuple. My Question, How To Call "AUTH_USER_MODEL" from forms.py. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils.translation import gettext_lazy as _ from django.utils import timezone class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) full_name = models.CharField(max_length=150) create_account = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_reviewer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] def __str__(self): return self.full_name settings.py #User model AUTH_USER_MODEL = 'authentication.Account' forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.conf import settings from .models import Account User = settings.AUTH_USER_MODEL class LoginForm(User): pass -
Django Media File Not Showing in Bucket
I have an issue trying to get my bucket to display both folders media and static. Currently when I collectstatic it only gets from static and not media. So It can obtain static from the bucket but not media files yet. How do I get media to show in my bucket? Policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicRead", "Effect": "Allow", "Principal": "*", "Action": [ "s3:GetObject", "s3:GetObjectVersion", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": "arn:aws:s3:::<AWS_STORAGE_BUCKET_NAME>/*" } ] } with the following settings.py # All of this is in my console.aws.amazon to configure aws s3 static files only # If I am in prod # IAM Management Console AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') # Amazon S3 Buckets AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = None AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_REGION_NAME = 'us-east-2' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'pages/static'), ] AWS_STATIC_LOCATION = 'static' STATICFILES_STORAGE = 'portfolio.storage_backends.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION) """ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') """ AWS_PUBLIC_MEDIA_LOCATION = 'media/public' DEFAULT_FILE_STORAGE = 'portfolio.storage_backends.PublicMediaStorage' AWS_PRIVATE_MEDIA_LOCATION = 'media/private' PRIVATE_FILE_STORAGE = 'portfolio.storage_backends.PrivateMediaStorage' # Fixes Found another file with the destination path """ STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', #'django.contrib.staticfiles.finders.AppDirectoriesFinder', #causes verbose duplicate notifications in django 1.9 … -
'list' object has no attribute '_meta' plese help me out i was stuck
enter image description here recently I want to edit the row of the table but stocked there for among 3 days help me out to get rid out of this -
Can't connect dat.gui in my javascript on my django server
I'm new in web dev and I´m trying to import the dat.gui package library in my javascript, but it isn't working :c I'm using python and django to make the server, and I used the mehtod that comes in the docs in the HTML downloading the package and writting the root manually. It seems to read the package in the html but I don't know why I can't do the samething on my Javascript. HTML: JAVASCRIPT: import * as DAT from '/package/build/dat.gui.min.js' -
No messages being sent by celery beat (using django-celery-beat)
I am in the process of upgrading to celery 5.x for a Django project. Since there is no longer a @scheduled_task annotation, I changed all of those to @shared_task and wrote some code to create CrontabSchedule instances and associate PeriodicTask instances with those for each task that should run on a schedule. I am invoking that from a beat_init signal receiver. I'm running celery worker & beat as separate processes. I am logging info from the function that sets up the CrontabSchedule and PeriodicTask instances, and I see that log output from the celery beat process. Immediately after that, I see a DatabaseScheduler: Schedule changed." message. That's all as expected and good. Subsequently, however, celery beat just sits and does nothing. beat never sends any messages, and as a result, celery worker never executes any scheduled tasks. In django-admin shell_plus, PeriodicTask.objects.all() shows me many scheduled tasks with schedules that all look as they should. Here's 1 example from the output that should be running once per minute, every day: <PeriodicTask: dhnetwork.tasks.send_queued_mail: {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59} {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23} * {1,2,3,4,5,6,7,8,9,10,11,12} {0,1,2,3,4,5,6} (m/h/dM/MY/d) America/Los_Angeles> Any ideas what I might be doing wrong and/or how to diagnose the problem? -
testing in Django
I am trying to test my Django application to get 100 % statement coverage. I Am using class-based view and overwriting some af the functionalities. One of them is the form valid in my AttendanceLogFormView in my views.py My question is how do I test that this method is working as it should with unit tests in Django? I am very new to testing so I very difficult for me to wrap me head around the concept I just know I need to test the if/else for statement coverage - but I don't know how? class AttendanceLogFormView(CreateView): model = AttendanceLog template_name = "attendancecode/Createattendancelog.html" form_class = AttendanceLogForm success_url = "/attendancecode/success/" # Checks if data input is valid and saves object def form_valid(self, form): obj = form.save(commit=False) user = "nadi6548" obj.date = date.today() getClass = Class.objects.get(name=obj.keaclass) getCourse = Course.objects.get(name=getClass.Course_name) getLocation = School.objects.get(id=getCourse.location_id) coords_1 = (getLocation.lat, getLocation.long) coords_2 = (obj.lat, obj.long) # check location and that student goes in the class if (geopy.distance.distance(coords_1, coords_2).km < 0.5) and Student.objects.get( username=user, Class_id=obj.keaclass): # check log is a code with correct info and correct date and that # student has subject + code is active if AttendanceCode.objects.filter( code=obj.attendanceCode, keaclass_id=obj.keaclass, subject_id=obj.subject_id, date=obj.date, isActive="True") and StudentHasSubject.objects.get( student_name_id=user, subject_name_id=obj.subject_id): … -
upload data using vanila javascript ajax and django1.11.17
using vanila javascript ajax and django1.11.17 , i wanna upload image with other data, and how to handle it in django. using vanila javascript ajax and django1.11.17 , i wanna upload image with other data, and how to handle it in django. var name=document.querySelector('#name').value; var lname=document.querySelector('#lname').value; var email=document.querySelector('#email').value; var password=document.querySelector('#password').value var CSRF=document.querySelectorAll('input')[5].value var file=document.querySelector('#file') var res=document.querySelector('.res') var formdata = new FormData(); formdata.append('image',file.files[0]); xhttp= new XMLHttpRequest(); xhttp.open('POST',"",true); xhttp.setRequestHeader("X-CSRFToken",pass); xhttp.setRequestHeader("content-type",'application/multipart/form-data'); xhttp.onload=function(){ if(this.status == 200){ res.innerText=this.responseText }else{ res.innerText='error' } } var data = {fn:name,ln:lname,em:email,pw:password,img:formdata} xhttp.send(JSON.stringify(data)) -
How do I match my bootstrap datepicker URL with my re_path on django?
I have this datepicker: <form class="d-flex justify-content-center ms-3" action="/" method="GET"> <input class="form-control me-3" type="date" name="date" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-secondary" type="submit"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" role="img" viewBox="0 0 24 24"><title>Search</title><circle cx="10.5" cy="10.5" r="7.5"/><path d="M21 21l-5.2-5.2"/></svg> </button> </form> When I select a date it returns an url like this: http://localhost:8000/?date=2021-12-15 The problem is I'm not being able to match it with my regular expression: re_path(r'^date=(?P<date>[0-9]{4}-?[0-9]{2}-?[0-9]{2})', DatePostListView, name='date-list') This regular expression works when the URL is: http://localhost:8000/date=2021-12-15 The problem is the "?" in the URL, but I don't know how to put that in my re_path (I have already tried with %3F and \? but doesn't work). The other solution may be modifying my datepicker, so I can get an URL like the one above when I pick a date, but I'm not sure how to do this. Hope someone can help me. Thanks -
How to add songs to my templates in views
if i post a song from my admin panel, i want the list of song to appear in the templates, i already created a models that allow me to post it, but i don't know how to create a views that allowed the song to appear in the templates, please how can i do this ? this is my empty views views.py from django.shortcuts import render from .models import Audio # Create your views here. def index(request): return render(request, 'index.html') this is my models.py i created models.py from django.db import models # Create your models here. class Audio(models.Model): book_title = models.CharField(max_length=100, null=False, blank=False) file = models.FileField(upload_to='file') author = models.CharField(max_length=100, null=False, blank=False) artist = models.CharField(max_length=100, null=False, blank=False) -
how to embed facebook video in django project
what is the easiest way to embed facebook live video or any facebook video in any django website ? I used https://github.com/jazzband/django-embed-video package but it's work only for youtube video . -
Django: Django_filters in a class-based views
I ask you if you know how put this filters : class CoursesFilters(django_filters.FilterSet): class Meta: model = Courses exclude = ('description') in this class view : class CoursesList(ListView): model = Courses template_name = 'courses_list.html' I used to build my applications using function-based views, and this is my first time use class-based views. Any idea? -
How to access HTTPS on development server
I have Django project, I tried to run develop SSL server by python manage.py runserver_plus --cert-file cert.crt, but anytime I get error Site doesn't reach, how i can fix it? I have mapped my hosts.ics file, tried also a sslserver, there is nothing working -
How to disable method in Django APIView?
My question is same title. How to disable method in Django APIView? for example, class A(APIView): permission_classes = [IsAuthenticated] def get(self, request): return JsonResponse({"message": "Hello, world!"}) I want to only get method allowed, How can I? -
Exception has occurred: AttributeError 'NoneType' object has no attribute 'split'. When debugging with Docker and VSCode
I'm setting up a debugger using docker-compose following this guide. I've modified the file manage.py to run debugpy when setting.DEBUG exists but when redding the settings file it throws an exception of 'NoneType' object has no attribute 'split'. Here are the files I'm using: .env.dev DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 0.0.0.0[::1] manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') # start new section from django.conf import settings if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import debugpy debugpy.listen(("0.0.0.0", 5678)) print('Attached!') # end new section try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Any ideas? -
Inheritance in Django: Make parent class fall back to child method
Tl;Dr: Circumvent that parents can not call child methods in python (I guess) Consider the following (simplified) django models were MaterialInstance and BookInstance both inherit Item. class Item(models.Model): """Represents an item that is physically in the library""" label = models.CharField(max_length=20, unique=True) @property def description(self) -> str: raise NotImplementedError class BookInstance(Item): """Represents a copy of a book that is physically in the library""" @property def description(self) -> str: return str(self.book) book = models.ForeignKey('Book', on_delete=models.RESTRICT) class MaterialInstance(Item): """Represents a instance of a material that is physically in the library""" @property def description(self) -> str: return str(self.material) material = models.ForeignKey('Material', on_delete=models.RESTRICT, null=True) I want to show all items (books AND material instances) in one table. One row should be a description (either the book title or the material name). It would be nice to use the following template (but this raises a NotImplementedError as the parent class does not try to call child methods. Any suggestions for a clever design that circumvents this problem? <table> <tr> <th>Label</th> <th>Description</th> </tr> {% for item in item_list %} <tr>{{ item.label }}</td> <td>{{ item.description }}</td> </tr> {% endfor %} </table> The final thing should look something like this |Label|Description| |---|---| |B1 | A Boring Book Title| |B2 … -
How can I filter on multiple NOT conditions in Django's ORM?
In Django 3.2, I have the following models: class Person(models.Model): name = models.CharField(max_length=100) class Employment(models.Model): owner = models.ForeignKey('Person', on_delete=models.CASCADE) title = models.CharField(max_length=100) full_time = models.BooleanField(default=True) class Car(models.Model): owner = models.ForeignKey('Person', on_delete=models.CASCADE) color = models.CharField(max_length=100) The Goal: Give me all people that drive a red car (unless they're a full-time firefighter) Here is what I thought would work: Person.objects.filter( ~Q(employment__title='firefighter', employment__full_time=True), car__color='red' ) However, this generates the following SQL: SELECT * FROM "person" INNER JOIN "car" ON ("person"."id" = "car"."owner_id") WHERE "car"."color" = red AND ( NOT ( EXISTS( SELECT (1) AS "a" FROM "employment" U1 WHERE U1."full_time" AND U1."owner_id" = "person"."id" ) AND EXISTS( SELECT (1) AS "a" FROM "employment" U1 WHERE U1."title" = firefighter AND U1."owner_id" = "person"."id" ) ) This in effect returns all people that drive a red car (unless they are a firefighter OR have full-time employment). Like all other filter keys, I would have expected the two conditions on the foreign relation to be ANDED. Why the unexpected behavior? What's the right way to write this so the sql looks like this:? SELECT * FROM "person" INNER JOIN "car" ON ("person"."id" = "car"."owner_id") WHERE "car"."color" = red AND ( NOT ( EXISTS( SELECT (1) AS … -
Django Annotation with boolean field ExpressionWrapper
I'm trying to create a high score statistic table/list for a quiz, where the table/list is supposed to be showing the percentage of (or total) correct guesses on a person which was to be guessed on. To elaborate further, these are the models which are used. The Quiz model: class Quiz(models.Model): participants = models.ManyToManyField( User, through="Participant", through_fields=("quiz", "correct_user"), blank=True, related_name="related_quiz", ) fake_users = models.ManyToManyField(User, related_name="quiz_fakes") user_quizzed = models.ForeignKey( User, related_name="user_taking_quiz", on_delete=models.CASCADE, null=True ) time_started = models.DateTimeField(default=timezone.now) time_end = models.DateTimeField(blank=True, null=True) final_score = models.IntegerField(blank=True, default=0) This models does also have some properties; I deem them to be unrelated to the problem at hand. The Participant model: class Participant(models.Model): # QuizAnswer FK -> QUIZ guessed_user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="clicked_in_quiz", null=True ) correct_user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="solution_in_quiz", null=True ) quiz = models.ForeignKey( Quiz, on_delete=models.CASCADE, related_name="participants_in_quiz" ) @property def correct(self): return self.guessed_user == self.correct_user To iterate through what I am trying to do, I'll try to explain how I'm thinking this should work: For a User in User.objects.all(), find all participant objects where the user.id equals correct_user(from participant model) For each participantobject, evaluate if correct_user==guessed_user Sum each participant object where the above comparison is True for the User, represented by a field … -
why doesn't django log the specified application?
I has some project with application named "work". The directory of the app also named work, and inside apps.py its also named "work", and in INSTALLED_APPS also, etc. And I try to log just the application into file. So. I have prescribed the following settings in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'file_logger': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' } }, 'handlers': { 'file_logger': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': './logging.txt', }, }, 'loggers': { 'work.views': { 'handlers': ['file_logger'], 'level': 'DEBUG', 'propagate': True, }, }, } I initialized inside my views.py (views.py of work app) logger like this: logger = logging.Logger(__name__) where __name__ is "work.views" (I checked this one via debugger) and I have some view, which I want to log: def view_timesheet(request, t_id=None): logger.warning('wwwwwwwwwwwwwwwww') # some code return HttpResponse('ok') but when I execute the code of this view, nothing is written to the file. With what "wwwwwwwww" gets logged in the console This confuses me, because it seems to me that I have done everything according to the documentation and everything should work A few more details: If I write "django" instead of "work.views" all django logs will end up in a file. This leads …