Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Django Website Not Displaying Expected Content
I'm new to Django and am building a site for reminders. However, I see a blank page on launch. My base.html has a form for reminders and a display section, index.html has a similar form, and styles.css is for styling. Static paths seem fine, server runs with no errors, and migrations are updated, but still no content. Here's my code: `base.html Reminder FormSet Reminder{% csrf_token %}{{ form.as_p }}Set ReminderReminders{% for reminder in reminders %}{{ reminder.time }} - {{ reminder.title }}: {{ reminder.message }}{% endfor %} ` index.html <form method="post">{% csrf_token %}{{ form.as_p }}<button type="submit">Set Reminder</button></form> styles.css *{margin:0;padding:0;box-sizing:border-box;}body{font-family:'Arial',sans-serif;background-color:#3618bb;color:#4c34a3;}.container{max-width:1200px;margin:0 auto;padding:20px;}h1,h2,h3{margin-bottom:20px;}input[type="text"],input[type="submit"]{padding:10px;margin-bottom:10px;}input[type="submit"]{cursor:pointer;background-color:#333;color:#8b1818;border:none;} Any ideas what's wrong? - 
        
embed video on website using django-embed-video
when run it gives an error: Exception Type: TemplateDoesNotExist at / Exception Value: video.html and also: return render(request,'video.html',{'obj':obj}) views.py: from django.shortcuts import render from .models import Item def video(request): obj = Item.objects.all() return render(request,'video.html',{'obj':obj}) video.html: {% load embed_video_tags %} <!doctype html> <html lang="ru"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Демо Bootstrap</title> </head> <body> <h1>Привет мир!</h1> {% block content %} {% for i in obj %} {% video i.video 'small' %} {% endfor %} {% endblock %} </body> </html> I searched how to fix the error on YouTube and did not find anything - 
        
nginx: serving uwsgi on same port in nginx.conf
I am new to nginx/uwsgi stuff. I have set up nginx to serve static HTML web pages, and uWSGI+DJango for web application. Currently, they are serving at different ports, like: - to access HTML pages: http://my.domain.com/ # port 80 - to access web application: http://my.domain.com:8000/app/** # port 8000 Currently they work fine individually. But my goal is to put them on same port so http://my.domain.com/app/** can access the web applications. Below is the current nginx.conf: ... server { listen 80; location / { root html; } } include conf.d/*.conf; ... Below is conf.d/webapp.conf: upstream django { server unix:///path/to/django/project/webapp.sock; } server { listen 8000; location / { uwsgi_pass django; include /path/to/uwsgi_params; } } Below is uwsgi.ini: [uwsgi] chdir=/path/to/django/project/ module=project.wsgi:application socket=/path/to/django/project/webapp.sock master=True vacuum=True daemonzie=/path/to/django/project/uwsgi.log and uwsgi was started by uwsgi uwsgi.ini. How can I achieve my goal? - 
        
change venv from python 3.5 to python 3.6; Gunicorn does not start
My app on python3.5 works well. But when I make the virtualenv with python3.6 and install the same requirements; Gunicorn doesn't start with below error message in jenkins: + supervisorctl restart myapp myapp: stopped myapp: ERROR (spawn error) and in log file it's written: supervisor: couldn't exec /home/jenkins/myapp/venv/bin/gunicorn: ENOENT supervisor: child process was not spawned Also, the gunicorn package version is 19.8.1. I updated it to 20.0.0 but it doesn't work Any help would be appreciated - 
        
How to install Wagtail 5.1 or above
I am using MacOS. I tried to install Wagtail 5.1 in a venv and I installed pip install wagtail. and wagtail start mysite mysite. Without using cd mysite pip install -r requirements.txt, I directly typed cd mysite and python manage.py migrate. That because I needed to install Wagtail 5.1 and not Wagtail 2.1. But when I tried to python manage.py migrate, It shows many errors including ModuleNotFoundError: No module named ‘wagtail.core’. How could I install Wagtail 5.1 or above as a fresh install? - 
        
Upload images with Django and Whitenoise
i have just deployed a web using Django on Heroku with static files served by whitenoise. All the static files created before deploying works fine but if i want to upload new image (from both admin page and custom form) the image can not be found like below. Any help would be appreciated Can find the image settings.py STATIC_URL = '/staticfiles/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_URL = '/staticfiles/assets/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles/assets/images') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) models.py class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) img = models.ImageField(null=True, default= 'default_product_image.jpg',blank=True) class Meta: verbose_name_plural = "Product Image" I tried uploading from both admin page and form that enable user to upload images but both result the same - 
        
Fetching image using react-pdf <Image> causes CORS issue, whearas it loads fine in React <img>
I've backend built with django and I've installed django-cors-headers to fix cors error. If I try to load images from backend, react is rendering for tag, but fetching image using react-pdf causes CORS error. Here's my react-pdf blank const QRCodeBlank = ({ students }) => ( <Document> <Page style={styles.body}> {students && students.map((student) => ( <View> <Image src={`https://backend.link/media/${student.photo}`} /> <Text>{student.name}</Text> </View> ))} </Page> </Document> ); I've installed django-cors-headers to fix this issue, but there is no any changes. Here's my django settings for django-cors-headers library: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app.apps.AppConfig', 'corsheaders', 'rest_framework', 'rest_framework_simplejwt' ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True - 
        
How do I validate a JWS with a public key
I'm using Saleor and have set up a webhook to my django server. According to their documentation there is in the header a JWS signature using RS256 with payload detached, to verify the signature you can use a public key, which can be fetched from http(s)://<your-backend-domain>/.well-known/jwks.json The JWS is in the format xxx..yyy, so there is no payload, instead the payload is directly in the request.body. The way I have understood JWTs and public keys is that you can verify that the payload is legit by using the token together with the public key to see that the payload was signed with someone using the private key. The problem I have is that I keep getting the exception jwt.exceptions.InvalidSignatureError: Signature verification failed. This is my code: @csrf_exempt @require_http_methods(["POST"]) def saleor_webhook(request): print("Saleor webhook received") jws_token = request.headers.get('Saleor-Signature') response = requests.get(JWKS_URL) jwks = response.json() jwk_dict = jwks['keys'][0] # Convert JWK to PEM public key public_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk_dict)) pem_public_key = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) pem_public_key = pem_public_key.decode("utf-8") # Here is where it fails... decoded = jwt.decode(jws_token, pem_public_key, algorithms=['RS256']) print(decoded) return HttpResponse(status=200) Not sure if this is the right way or not, but I tried to also base64 encode the request.body and put it … - 
        
How do I setup CSRF token for purely REST API communication between two Django applications?
I have two separate backends both built with Django that I want to communicate with each other. Requests to the GET endpoints worked fine but POST requests gave me the following error: Forbidden (CSRF cookie not set.): /endpoint/path/ And the instructions from Django mention setting {% csrf_token %} in "any template that uses a POST form". But I have no templates! It's just an API. How do I get around this error? - 
        
download not working and image not showing
I want to create a download link using the anchor tag but it is not working and the image is not showing either <td><img src="{{book.book_image}}" alt="{{book.name}}" width="60px" height="50p"></td> <td>{{book.book_name}}</td> <td>{{book.author_name}}</td> <td>{{book.subject}}</td> <td><a href="{{book.file}}" download>Download</a></td> models.py class Book(models.Model): book_image = models.ImageField(upload_to="images/", blank="") book_name = models.CharField(max_length=150) author_name = models.CharField(max_length=200) quantity = models.IntegerField(default=1) file = models.FileField(upload_to="files/", null=True, verbose_name='file ') subject = models.CharField(max_length=2000) book_add_time = models.TimeField(default=timezone.now()) book_add_date = models.DateField(default=date.today()) - 
        
postgres connection test always succeeds
I was making TDD tests for my django projects to test the PostgresQL connection the i realized connections tests alwayse sucseeds even when the database is not available. Could anybody tell what the problem is? Here's my project repository: https://github.com/PeymaanEsi/alone/tree/dev (Database configuration in docker compose is commented) ~/Desktop/alone$ docker compose up [+] Running 2/0 ✔ Container db Created 0.0s ✔ Container alone Created 0.0s Attaching to alone, db db | db | PostgreSQL Database directory appears to contain a database; Skipping initialization db | db | db | 2023-09-01 20:03:03.391 UTC [1] LOG: starting PostgreSQL 15.4 on x86_64-pc-linux-musl, compiled by gcc (Alpine 12.2.1_git20220924-r10) 12.2.1 20220924, 64-bit db | 2023-09-01 20:03:03.391 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db | 2023-09-01 20:03:03.391 UTC [1] LOG: listening on IPv6 address "::", port 5432 db | 2023-09-01 20:03:03.394 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db | 2023-09-01 20:03:03.399 UTC [24] LOG: database system was interrupted; last known up at 2023-09-01 16:14:25 UTC db | 2023-09-01 20:03:03.435 UTC [24] LOG: database system was not properly shut down; automatic recovery in progress db | 2023-09-01 20:03:03.438 UTC [24] LOG: redo starts at 0/4138D08 db | 2023-09-01 20:03:03.438 UTC [24] WARNING: … - 
        
How to create self-signed SSL certificate in pure python? (Without any additional installation like openssl or mkcert)
There are similar questions like this which did not have any good answer, or linked to scripts that were very old. I have an open-source web app made using django that people can install on their local networks. I want to implement a quick, automated set up of the web app, with minimal technical know-how. One of the tasks involved is generating self-signed SSL certificates. However, since I do not know in advance what OS they would be using, I wish the certificate stuff to be done exclusively using python, to ensure platform independence. Common methods like using OpenSSL includes OS-specific installation of those libraries, which I do not want. How can I make secure self-signed ssl certificates exclusively through python and no additional installations like OpenSSL or mkcert? - 
        
Django CRSF across different origins for login request
I have been struggling and doing research for couple of days. I am currently use Django with Django rest_framework and django-allauth to build backend APIs and the authentication workflow. Everything runs prefect by hosting everything onto the same origin VM(A). Now due to requirement, I need to separate frontend login and backend API into two different origin. (A & B) APIs are behind the proxy. Instead of using django-allauth default server rendered login page(which auto set the csrf in {% csrf_token %}) I have made a simple login.html and put it into host A under apache /var/www/html/: <form class="login" method="POST" action="https://B.com/accounts/login/"> <input id="csrf" type="hidden" name="csrfmiddlewaretoken"> <p> <label for="id_login">Login:</label> <input type="text" name="login" placeholder="Username or e-mail" autocomplete="email" required="" id="id_login"> </p> <p> <label for="id_password">Password:</label> <input type="password" name="password" placeholder="Password" autocomplete="current-password" required="" id="id_password"> </p> <button type="submit">Sign In</button> </form> <script type="text/javascript"> window.onload = function(){ // Get csrf from B and set into cookie 'getToken' API is defined below $.ajax({ url: "https://B.com/getToken", type: 'GET', dataType: 'json', success: function(res) { console.log(res); $('#csrf').val(res.token); document.cookie = 'csrftoken=' + res.token; } }) }; </script> When the login.html is rendering it will make a GET request to the backend(B) API (/getToken) to fetch the csrftoken and save into the cookie and csrfmiddlewaretoken … - 
        
Why does pydoc work for some Django folders and not others? How to debug it?
I am using Django 4.2, and after setting DJANGO_SETTINGS_MODULE appropriately, I ran python -m pydoc -b When I visit the pydoc page, a lot of it produces pydoc, even within the modules of my Django project and application. However, occasionally it says: ErrorDuringImport: problem in myapp.mymodule - AppRegistryNotReady: Apps aren't loaded yet. It says this, for example, in the admin module (i.e. admin.py). Why would it work some times and not other times? I imagine it's some particular import? How do I figure out which one? - 
        
How can I efficiently retrieve a users feed in a social media app with Django
I am new to programming and new to Django and I am trying to design my first social media app. I wanted to see if theres an efficient way of retrieving a users feed that would result in quick retrieval of the users feed without being intensive on the database. I want to learn what the best practices are to follow to construct efficient API views. Provided below are my current User model, Follow model, and API view to retrieve a users feed. I was wondering what improvements I could make to my current implementation so I could learn more about Django and how to construct an efficient app. Currently, my API view retrieves all of the users the requesting user is following and then retrieves Posts made by those users. However if the user is following a lot of people, the query to get a list of all the users the requesting user is following might be inefficient, at least I think so. Would there be a better implementation to perform so I can get the users feed that would not be intensive in terms of database retrieval? I have the following User model: class User(AbstractUser): # Additional fields … - 
        
AWS EC2 Instance get slow but sometimes it works fine
I have a basic blog application made in Django and Python is hosted on AWS EC2 t2.micro using NGINX. It used PostgreSQL as database. The website loads fine most of the time but sometimes it takes too much time to load. Sometimes even the Django admin panel takes more time to load. I checked the monitor section of my EC2 instance and it all seems to be fine. Here is an screenshot. I also checked the memory and storage using free -m and top command but all seems to be fine. I am not sure what wrong in here. If anyone have faced this similar issue or know how to debug such things please let me know. Thanks in advance - 
        
How to modify an image before saving it in the database in Django?
I took an image as the input by the user via a form, I increased its brightness using Pillow, and now wish to save the image in the database. I am having trouble trying to modify the form with the new image so that I can save it. Please help me out. if form.is_valid(): input = form.save(commit=False) input.owner = request.user image = Image.open(input.image) # Enhance Brightness curr_bri = ImageEnhance.Brightness(image) new_bri = 2.5 # Brightness enhanced by a factor of 2.5 img_brightened = curr_bri.enhance(new_bri) image_file = ImageFile(img_brightened, name=None) form_image = ImageClient(image=image_file) input.image = form_image input.save() return redirect('profile') - 
        
UnicodeDecodeError when runvsever Django
Have a problem when starting local django server. When trying to run: python manage.py runserver or python manage.py runserver 127.0.0.1:8080 an error occurs: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc2 in position 55: invalid continuation byte Full error log: (my_env) D:\mysite\>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified some issues: WARNINGS: ?: (2_0.W001) Your URL pattern '^article/(?P<pk>\d+)/bookmark/$' [name='article_bookmark'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). System check identified 9 issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 136, in inner_run self.check_migrations() File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 574, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user_brad\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, … - 
        
Google social login with Django + allauth + dj_rest_auth + Expo fails with "Error retrieving access token"
We are using Django with a combination of allauth and dj_rest_auth as backend and Expo for building mobile frontend. We are currently facing an issue after logging in with Google Social Login. After setting up the google console for IOS and adding the corresponding provider in django, we can retrieve the credentials from google such as access_token, id_token and code. We have an endpoint in our backend where we should send the code property. This endpoint calls the view that inherits from SocialLoginView (from dj_rest_auth). When we are calling this endpoint with the corresponding code we are facing an issue that tells us: allauth.socialaccount.providers.oauth2.client.OAuth2Error: Error retrieving access token: '{ "error": "invalid_request", "error_description": "You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy for keeping apps secure. You can let the app developer know that this app doesn't comply with one or more Google validation rules."}' Traceback (most recent call last): File "/Users/.../backend/venv/lib/python3.10/site-packages/allauth/socialaccount/providers/oauth2/client.py", line 93, in get_access_token raise OAuth2Error("Error retrieving access token: %s" % resp.content) After some researches we saw that apparently the issue could come from a bad redirect_uri. Since there is no way to set redirect URI in the google cloud console (in … - 
        
Django PWA serviceworker.js code is showing on home page
When I go to home page of my website, I'm met with code of my serviceworker.js which looks like this: var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '/base_layout' ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('/base_layout')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); This is a code from this tutorial. After every "hard refresh" (CTRL + F5 or CTRL + R) it shows my regular home page and the link doesn't change at all. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PWA_SERVICE_WORKER_PATH = os.path.join(BASE_DIR, 'static/scripts', 'serviceworker.js') ... PWA_APP_NAME = 'Timetable Ease' PWA_APP_DESCRIPTION = "Timetable Ease PWA" PWA_APP_THEME_COLOR = '#3D36FF' PWA_APP_BACKGROUND_COLOR = '#aaaadd' PWA_APP_DISPLAY = 'standalone' PWA_APP_SCOPE = '/' PWA_APP_ORIENTATION = 'any' PWA_APP_START_URL = '/' PWA_APP_STATUS_BAR_COLOR = 'default' PWA_APP_ICONS = [ { 'src': 'static/images/logo.png', 'sizes': '160x160' } ] PWA_APP_ICONS_APPLE = [ { 'src': 'static/images/logo.png', 'sizes': '160x160' } ] PWA_APP_SPLASH_SCREEN = [ { 'src': 'static/images/logo.png', 'media': '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)' } ] PWA_APP_DIR = 'ltr' PWA_APP_LANG = 'en-US' PWA_APP_DEBUG_MODE = False project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ … - 
        
Proper way of creating a video streaming server
I am working with the Django framework and I need to create a video streaming server, this is when one user records a video and we broadcast it to thousands of other users through the server. At one moment there can be many broadcasts at once, which will be on different URLs. I'm not sure that Django is the right tool for this kind of work, so I'm leaning towards the socket library in the Python programming language, as it can use the UDP protocol and I can implement everything asynchronously and connect to the project Django-ORM. Another option is Fast API, it is asynchronous, but if I'm not mistaken it works only with TCP, which is not the best option for streaming. I will have only a few days to implement the project, and it will be necessary to start soon, unfortunately, I will not have time for experiments. Can anybody tell me if I am moving in the right direction? Or should I use other tools for this? - 
        
PyShark+Django : Unable to make async call when pyshark is used in a Django view
I am using pyshark module in a Django view to get the ports breakdown from an uploaded PCAP file. views.py class ProtocolAnalysisView(APIView): parser_classes = (MultiPartParser,) def analyze_pcap(self, pcap_file): res = {} capture = pyshark.FileCapture( pcap_file.temporary_file_path(), keep_packets=True) hl_dict = {} tl_dict = {} try: i = 0 while True: hl = capture[i].highest_layer tl = capture[i].transport_layer if hl not in hl_dict: hl_dict[hl] = 0 if tl not in tl_dict: tl_dict[tl] = 0 hl_dict[hl] += 1 tl_dict[tl] += 1 i += 1 except KeyError: capture.close() res["tcp_packet_counts"] = tl_dict.get("TCP", 0) res["udp_packet_counts"] = tl_dict.get("UDP", 0) res["transport_layer_breakdown"] = [ {"transport_layer_protocol": key, "count": value} for key, value in tl_dict.items() ] res["protocol_breakdown"] = [ {"highest_layer_protocol": key, "count": value} for key, value in hl_dict.items() ] return res def post(self, request, *args, **kwargs): serializer = PcapFileSerializer(data=request.data) if serializer.is_valid(): pcap_file = serializer.validated_data['pcap_file'] res = self.analyze_pcap(pcap_file) return Response({"data": res}, status=200) else: return Response(serializer.errors, status=400) The serializer used here: class PcapFileSerializer(serializers.Serializer): pcap_file = serializers.FileField( allow_empty_file=False, allow_null=False, help_text="Upload a pcap file.") When I POST the a using form-data, Django throws the below exception: Exception Value: There is no current event loop in thread 'Thread-1 (process_request_thread)'. Using library like scapy and dpkt is not an option for me. So I dig deep anf got to … - 
        
django how to use index counter on django template
i try using this put output will be empty i wont to show the pic and date from api calling to django template --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - 
        
Celery in Django: celery beat doesn't work
settings.py: #CELERY CELERY_BROKER_URL = 'redis://localhost:6379' # URL для Redis брокера CELERY_RESULT_BACKEND = 'redis://localhost:6379' # URL для Redis бэкенда результатов # Настройки для Celery Beat (периодические задачи) CELERY_BEAT_SCHEDULE = { 'execute_daily_task': { 'task': 'your_app.tasks.execute_daily_task', # Путь к вашей задаче 'schedule': crontab(minute=47, hour=18), # Запускать в полночь каждый день }, } root init.py: # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) celery.py in root directory: # celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # Установка переменной окружения DJANGO_SETTINGS_MODULE для работы с Django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sites.settings') # Создание экземпляра Celery app = Celery('sites') # Загрузка конфигурации Celery из настроек Django app.config_from_object('django.conf:settings', namespace='CELERY') # Автоматическое обнаружение и регистрация задач в приложениях Django app.autodiscover_tasks() tasks.py in users app: from celery import shared_task from django.core.mail import send_mail from datetime import date from .models import Company @shared_task def execute_daily_task(): print('celery is working') ran beat, worker, django-runserver in 3 powershells: celery -A sites worker --loglevel=info -------------- celery@LAPTOP-2554OM7H v5.3.3 (emerald-rush) --- ***** ----- -- ******* ---- Windows-10-10.0.22621-SP0 2023-09-01 18:45:29 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: … - 
        
request = self.context.get('request') , give me'NoneType' object has no attribute 'data'
I'm trying to exclude certain fields from being displayed in the list view of my serializer. To achieve this, I have overridden the to_representation method. However, when I attempt to access the 'request' object using request = self.context.get('request'), I encountered an error stating "'NoneType' object has no attribute 'data'. this is serializer.py from rest_framework import serializers from todo.models import Task class TodoSerializer(serializers.ModelSerializer): short_content=serializers.ReadOnlyField(source='get_short_content') author = serializers.CharField(source="author.username", read_only=True) class Meta: model = Task fields =['id','title', 'author' ,'details' ,'short_content','isCompleted','created_date','updated_date'] read_only_fields=['author'] def to_representation(self,instance): request=self.context.get('request') rep =super().to_representation(instance) print(request.data) if request.parser_context.get('kwargs').get('pk'): rep.pop('short_content',None) else: rep.pop('details',None) return rep Any insights into why I might be receiving this error and how to resolve it would be greatly appreciated. Thank you!