Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IHow do I coonect a webapp to a thermal printer for printing
I built a web app and bought a thermal printer, I geenrate recipt from the web app, but don't know how to send it to the printer to print, also the connection is not stable. which printer is cost effective and I can use that has stable connection How can I send the recipt for printing directly from my web app without third party intervention I bought a printer already but I have to reconnect on eevry print, and it hard even reconnecting, am using django for my backend and react for front end. I have not been able to print directly from my app, all other printer were through third party app -
Ubuntu 22.04 Django cronjob - No MTA installed, discarding output - Error
If I run this source /var/www/django/env/bin/activate && cd /var/www/django/ && python manage.py cron in the cockpit gui terminal (ubuntu-server 22.04) an email is sent. But if I run it as a cronjob, in crontab: * * * * * administrator source /var/www/html/django/env/bin/activate && cd /var/www/html/django/ && python manage.py cron I'm getting the error (CRON) info (No MTA installed, discarding output) What I'm missing? -
How to create an update function for a Django AbstractUser
I created signup/login with 'UserCreationForm'. How can I make update possible by using 'UserChangeForm'? models.py from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): pass def __str__(self): return self.username forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from.models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('first_name', 'last_name', 'username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('first_name', 'last_name', 'username', 'email') views.py from django.shortcuts import render, redirect # Create your views here. from django.urls import reverse_lazy from django.views.generic.edit import CreateView from django.views import View from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class SingUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' #выдает ошибку class CustomUserUpdateView(View): def get(self, request, *args, **kwargs): user_id = kwargs.get("id") user = CustomUser.objects.get(id=user_id) form = CustomUserChangeForm(instance=user) return render( request, "users/update.html", {"form": form, "user_id": user_id} ) def post(self, request, *args, **kwargs): user_id = kwargs.get("id") user = CustomUser.objects.get(id=user_id) form = CustomUserChangeForm(request.POST, instance=user) if form.is_valid(): form.save() return redirect("users_list") return render( request, "users/update.html", {"form": form, "user_id": user_id} ) I've been trying to create update with inheritance of the View class including 'get/post' methods, but it raises an error CustomUser matching query does not exist. I did everything google told me to activate get/post … -
Django ORM gives duplicates in filtered queryset
I have a django app. I use the ORM to run some queries. It appears I have some duplicates in my result. While I can simply add a distinct() I would like to understand what is going on. Here are my models: class Person(models.Model): created = models.DateTimeField(auto_now_add=True) active_stuffs = models.ManyToManyField(Stuff, related_name="persons") waiting_stuffs = models.ManyToManyField(Stuff, related_name="persons_waiting") cancelled_stuffs = models.ManyToManyField(Stuff, related_name="persons_cancelled") # ... other fields class Stuff(models.Model): name = models.CharField(null=False, blank=False, max_length=150,) # ... other fields Here is the query: queryset = Person.objects.filter( Q(active_stuffs__id=some_id) | Q(cancelled_stuffs__id=some_id) | Q(waiting_stuffs__id=some_id) ) What I don't understand, is the following results: queryset.count() -> 23 Person.objects.filter(Q(active_stuffs__id=some_id)).count() -> 16 Person.objects.filter(Q(cancelled_stuffs__id=some_id)).count() -> 0 Person.objects.filter(Q(waiting_stuffs__id=some_id)).count() -> 6 An instance of Stuff can only be in either active_stuffs, cancelled_stuffs or waiting_stuffs. I checked the Person instance that is duplicated, and the Stuff instance I'm looking for is only in the waiting_stuffs field... So, where could this duplicate come from? -
Architecture Advice for Research Portal (DRF + Next.js)
I’m currently developing a research portal locally on my Mac using Django REST Framework (DRF) for the backend and Next.js for the frontend. We’re now preparing to move the project to a Test server environment. Our university’s IT Services team has asked for deployment specifications, including whether we need two separate servers for the frontend and backend. The database will be hosted on a dedicated server, and everything will be placed behind a load balancer and firewall. Given that this portal will host research data (real-time Data entry forms, real-time reports, etc), I’m trying to understand the best practices for security and performance: Is it recommended to host the frontend and backend on separate servers? What are the pros and cons of separating them vs. hosting both on a single server? What web servers are commonly used in this kind of setup? Are there any other security or architectural considerations I should be aware of? Have read few blogs and googled around but mixed responses and not specific to my requirements. SO asking here as I do not have much IT people experienced in this stack in our Uni. -
why when adding a cron job , it doesn't work? [closed]
I do add a cron job and it is shown when using crontab show but the function in python doesn't get executed and I tried to run the function in the python interpreter and it works , so I guess the problem is in crontab but couldn't resolve it and I am using docker and here is my repo : https://github.com/RachidJedata/Cron_with_django I did add the cron job as shown below but it doesn't get executed and I have set the log to a file cron.log but it is always empty: root@143ee1babb0b:/app# python manage.py crontab add adding cronjob: (4500c7eba7f00df4e625ceb624206d74) -> ('* * * * *', 'crypto.cron.fetchCryptoData >> /cron/cron.log 2>&1') root@143ee1babb0b:/app# cat ../cron/cron.log root@143ee1babb0b:/app# and below is the proof that my cron job is added but it is not being executed : python manage.py crontab show Currently active jobs in crontab: 0352d2a16547ccdea8c7d44dcac8cf1d -> ('* * * * *', 'crypto.cron.fetchCryptoData >> cron/cron.log 2>&1') root@94461ae7b66f:/app# -
OIDC django-allauth - kid lookup uses x509 instead of jwk when upgraded to 65.11.0?
We recently upgraded to django-allauth[mfa, socialaccount]==65.11.0 where we are using an OIDC-provider that extends OAuth2Client and we discovered that one of our SocialApplication configs that is connected with an Azure app registration stopped working after the bump. Before the version bump, successful authentication was made but now we get an allauth.socialaccount.providers.oauth2.client.OAuth2Error: Invalid 'kid' error. Digging a bit deeper we can see that it's jwtkit.py in allauth/socialaccount/internal that calls lookup_kid_pem_x509_certificate(keys_data, kid) to check if the kid is valid but the variables does not have the expected structure and rather fits lookup_kid_jwk(keys_data, kid) instead. I can't seem to find any documentation or pointers to where or how i can direct the call to use lookup_kid_jwk(keys_data, kid) since the config is the same as before the version bump. Anyone else having the same issue or any input here? The config at SocialApplication.settings looks like {"server_url": "https://login.microsoftonline.com/abc123/v2.0/.well-known/openid-configuration", "oauth_pkce_enabled": false} -
Django App Deploy Error in AWS ECR+EC2 setup
enter image description here I have installed Docker & AWS CLI on EC2 instance, pull docker image from ECR to EC2, then have run the Django container on EC2 machine. As of now trying to deploy with http, later will shift to https. Want to deploy withing free tier. I am facing attached error, what could have gone wrong? -
Django vs FastAPI vs ASP.NET in 2025 and beyond: which framework is best considering pay, future growth, and industry demand? [closed]
I have basic understanding and some experience with Django, FastAPI, and ASP.NET. Looking ahead to 2025 and beyond, I want to know which of these frameworks is likely to be the best choice in terms of: Salary/pay potential Industry demand and adoption Future growth and long-term relevance I’m not asking “which one should I learn first,” but rather looking for insights into the career and industry trends for these frameworks. Which one is most promising for developers in the coming years? -
Django, xhtml2pdf cannot add to canvas properties
I'm trying to create some pdf bar charts in my Django project using xhtml2pdf (which I find easier to use than ReportLab and better than Weasyprint). I can use the example given in the xhtml2pdf docs using my own data and labels and can change any of the existing canvas properties but cannot add any new properties. My understanding is that the canvas properties that xhtml2pdf uses are derived from ReportLab Graphics converted to a dictionary. My HTML code is: <html lang="en"> <head> <meta charset="UTF-8"> <title>Vertical bars</title> </head> <body> <canvas type="graph" width="350" height="150"> { "data": [{{ data1 }}, {{ data2 }}], # <-- Can add data & labels here "labels": {{ labels }}, "title": {"_text": "Number of Orders by Destination", "x": 290, "y": 155}, "x_title": 290, "y_title": 155, "type": "verticalbar", "fillColor" : "#000000", # <-- (added) cannot change color "x": 150, "y": 50, "barLabelFormat": "%2.0f", "barLabels": {"nudge": 7}, "valueAxis": {"valueStep": 40, "valueMin" : 0}, # <-- (added) property ignored "categoryAxis": { "strokeColor": "#000000", # <-- changed "labels": {"angle": 0, "boxAnchor": "n", "dy": -6, "fontName": "Helvetica", "fontSize": 8, "textAnchor": "middle"} } } </canvas> </body> </html> How can I add properties to an xhtml2pdf html page? Specifically what I want to do … -
I restored my DB from a wrong backup file where the table I need didn't exist but I have migrations that create that table
I had a blog_user table in my DB, but accidentally restored a wrong backup.sql file so it disappeared. I don't have blog_user table in DB right now, but I have a migration creating user model. I tried to re-run the migrations so that they re-create the table. Like this: python manage.py migrate blog zero or python manage.py migrate blog zero --fake But get errors: I get the errors: Traceback (most recent call last): File "C:\Python_scripts\blog_and_shop\manage.py", line 22, in main() File "C:\Python_scripts\blog_and_shop\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python_scripts\blog_and_shop.venv\lib\site-packages\django\core\management_init_.py", line 442, in execute_from_command_line utility.execute() File "C:\Python_scripts\blog_and_shop.venv\lib\site-packages\django\core\management_init_.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python_scripts\blog_and_shop.venv\lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python_scripts\blog_and_shop.venv\lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) File "C:\Python_scripts\blog_and_shop.venv\lib\site-packages\django\core\management\base.py", line 107, in wrapper res = handle_func(*args, **kwargs) File "C:\Python_scripts\blog_and_shop.venv\lib\site-packages\django\core\management\commands\migrate.py", line 303, in handle pre_migrate_apps = pre_migrate_state.apps File "C:\Python_scripts\blog_and_shop.venv\lib\site-packages\django\utils\functional.py", line 47, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python_scripts\blog_and_shop.venv\lib\site-packages\django\db\migrations\state.py", line 566, in apps return StateApps(self.real_apps, self.models) File "C:\Python_scripts\blog_and_shop.venv\lib\site-packages\django\db\migrations\state.py", line 637, in init raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'blog.user', but app 'blog' doesn't provide model 'user'. The field blog.Comment.author was declared with a lazy reference to 'blog.user', but … -
How can I redirect to the same page after submitting a form using Django and display the submitted data on that same page?
This is my class based view function Whenever the use finishes to enter the required data and click the submit button. I want the page to reload so user can see the data they have submitted. I don't want to redirect the user to another page. But the app behaves differently. I'm trying to see how I can manage to make this work please Any hint will be helpful. Thank you in advance. class homeView(View): def get(self, request): data = recipemeal.objects.all().order_by("-id") context ={ "recipes":data, "form":RecipeForm() } return render(request, "index.html", context) def post(self, request): form = RecipeForm(request.POST) data = recipemeal.objects.all().order_by("-id") if form.is_valid(): form.save(commit=True) return HttpResponseRedirect(reverse("home")) else: context = { "recipes": data, "form": RecipeForm() } return render(request, "index.html", context) urlpatterns = [ path("", views.homeView.as_view(), name="home"), ] <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h2>Hi there, my name is Wilkenson</h2> <section> <div class="container"> <div> <form method="POST"> {% csrf_token %} {{ form }} <button class="btn" type="submit">Add Data</button> </form> </div> <div> <form action="/" method="POST"> {% csrf_token %} <button class=" button generate-pdf">Generate Plan</button> </form> </div> {% if recipes %} <table> <tr> <th>Recipe No.</th> <th>Day-Time</th> <th>Recipe Name</th> <th>Description</th> <th>Action</th> </tr> {% for item in recipes %} <tr> <td>{{item.id}}</td> <td>{{item.date}}</td> <td>{{item.title}}</td> … -
How to secure a refresh token in a JWT system when it's sent as an httpOnly cookie
In my React + Django project, I’m currently sending the refresh token as an HttpOnly cookie. The problem with HttpOnly cookies is that they are automatically sent by the browser, which makes them vulnerable to CSRF attacks. To address this, I decided to add a CSRF token for the refresh request. However, the issue I’m facing is that I’m unable to read the CSRF token using JavaScript. I think this is because my frontend and backend are on different domains. When I searched online, I found that cross-site cookies can’t be read by JavaScript. If that’s true, what are the possible ways to protect the refresh token request? -
custom filter for filter_horizontal admin in django
I have the following models where a deck have a many to many relationship with problems and problems can have tags from django.utils import timezone from django.db import models from taggit.models import TaggedItemBase from taggit.managers import TaggableManager # Create your models here. class TaggedProblem(TaggedItemBase): content_object = models.ForeignKey('Problem', on_delete=models.CASCADE) class Problem(models.Model): title = models.CharField(max_length=200) body = models.CharField(max_length=10000) pub_date = models.DateTimeField("date published", default=timezone.now()) tags = TaggableManager(through=TaggedProblem) class Meta: verbose_name = "problem" verbose_name_plural = "problems" def __str__(self): return self.title class Deck(models.Model): name = models.CharField(max_length=200) problems = models.ManyToManyField(Problem) def __str__(self): return self.name then for the admin i have the following from django.contrib import admin # Register your models here. from .models import Problem,Deck class DeckAdmin(admin.ModelAdmin): filter_horizontal = ('problems',) admin.site.register(Deck, DeckAdmin) admin.site.register(Problem) and the admin looks like this well what i want to do is to have a custom filter to filter the available problems, the filter must be an interface where i can include and exclude tags associated with the problems, so i want to replace the filter search box with something like this so i can filter the problems by tags and then add then to the deck, how can i achieve that functionality?, i am new to django and have no idea … -
CheckConstraint in Django model not triggering in unittest.TestCase (AssertionError: IntegrityError not raised)
I have a Model class with a series of constraints that I am attempting to test, and I am unable to get these constraints to return an IntegrityError in testing. The class is as follows: from django.db import models from django.db.models import CheckConstraint, Q, UniqueConstraint class Products(models.Model): sku = models.CharField(primary_key=True, max_length=8) barcode = models.CharField(unique=True, max_length=14, blank=True, null=True) name = models.TextField(blank=True, null=True) rrp = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) status = models.TextField() manufacturer = models.TextField(blank=True, null=True) brand = models.TextField(blank=True, null=True) country_of_origin = models.TextField(blank=True, null=True) last_updated = models.DateField(blank=True, null=True) date_published = models.DateField(blank=True, null=True) exclusive = models.BooleanField(blank=True, null=True) class Meta: managed = False db_table = 'product' constraints = [ CheckConstraint( condition=Q(status__in=['Draft', 'Live', 'Discontinued']), name='check_status', violation_error_message="status field must be on of the following: 'Draft', 'Live', 'Discontinued'", ), CheckConstraint( condition=~(Q(date_published__isnull=False) & Q(status__in=['Draft', 'Discontinued'])), name='check_date_published', violation_error_message="Product with status 'Draft' or 'Discontinued' cannot have a date_published value" ), UniqueConstraint(fields=['barcode'], name='unique_barcode'), UniqueConstraint(fields=['sku', 'exclusive'], name='unique_sku_and_exclusive'), UniqueConstraint(fields=['sku', 'status'], name='unique_sku_and_status') ] The 'managed' value is flipped in 0001_initial.py when tests are run. The IntegrityError I'm using is from django.db.utils and not sqlite3, however the save() method isn't returning any exceptions to begin with, so the issue is not coming from the wrong version of IntegrityError. from django.db.utils import IntegrityError from django.test import … -
Issue with connecting Mongodb Atlas with Django using Mongoengine
I have created cluster using free tier in Mongodb Atlas and also it connected with my current IP address. When I am running python manage.py runserver it gives me error-ServerSelectionTimeoutError at /. However if I change the IP address to 0.0.0.0/0 then it gets connected and showing the data in the browser. Kindly suggest me how to get successful connection? Following are the settings I have added in django application: .env file: MONGODB_NAME=db_name MONGODB_HOST=host MONGODB_USER=user MONGODB_PASSWORD=password Django settings.py: from dotenv import load_dotenv import mongoengine, os load_dotenv() MONGODB_NAME=quote_plus(os.environ.get('MONGODB_NAME')) MONGODB_HOST=quote_plus(os.environ.get('MONGODB_HOST')) MONGODB_USER = quote_plus(os.environ.get('MONGODB_USER')) MONGODB_PASSWORD = quote_plus(os.environ.get('MONGODB_PASSWORD')) atlas_uri = f"mongodb+srv://{MONGODB_USER}:{MONGODB_PASSWORD}@{MONGODB_HOST}/{MONGODB_NAME}?retryWrites=true&w=majority&appName=Cluster0" mongoengine.connect( db=MONGODB_NAME, host=atlas_uri, alias="default", tls=True ) -
How to make Django more secure? [closed]
I came across this package that helps with Django security. It feels really comprehensive while still being easy to use — not too complicated. Package: https://github.com/xo-aria/django-secux I gave django-secux a try in one of my test projects, and so far it looks solid. But I'm curious to know: Has anyone here used it in production? Do you think it's safe and trustworthy enough for real projects? -
Best way to use docker with Django. Containerize ?, or all in a container?
I've read some tutorials about docker and django : some guys "containerize" an existing app already installed locally. and others install Django in a docker-compose and a Dockerfile (using pip for example), with volumes indeed. So "nothing" is installed locally, all the app is in a container. Accessing directly the container. Why is the best way ? Have you some relevant example ? F. -
How can I securely encrypt spatial fields (GeoDjango / PostGIS) in Django?
I’m working on a Django project with GeoDjango models that store user location data (e.g., PointField, LineStringField). Because location data is highly sensitive, I want to ensure it’s secured (?encrypted) at rest in the database. The challenge is that most Django field encryption libraries (like django-cryptography) work well for standard CharField or TextField, but don’t appear to support spatial fields directly. My requirements are: I don’t need to run spatial queries in PostGIS (like ST_Contains, ST_Distance, etc., although it would be a bonus if I could maintain this functionality of GeoDjango) — I can handle geometry operations in Python (Shapely/GEOS) after decryption. I do want the raw data encrypted in the database so that DB admins can’t see exact coordinates. Ideally, I’d like to keep using Django’s model field API so that saving/retrieving encrypted geometries feels natural. Has anyone implemented a secure way to encrypt GeoDjango fields? Any examples or best practices would be greatly appreciated! -
Pytest-django database not rolled back with pytest-asyncio
For context, I am trying to test a WebSocket connection made through Django, so I need to set up some async tests with database support. To do so, I have set up pytest-django and I have some trouble understanding the django_db decorator's behavior in async contexts. django_db has a parameter transaction which defaults to False. With this setting, the test class is supposed to act as django.test.TestCase which runs all tests in a transaction which is rolled back at the end of the test. However, in an async context, the objects created within a test seem to persist in other tests. Setting @pytest.mark.django_db(transaction=True) does make the tests pass, but increases test duration as actual modifications are made to the database. Here are quick examples: import pytest from cameras.models import CameraGroup as MyObject @pytest.mark.django_db @pytest.mark.asyncio class TestAsync: async def test_1(self): # OK await MyObject.objects.acreate(name="same-name1") assert await MyObject.objects.acount() == 1 async def test_2(self): # FAILS # This should not see test_1's object if rollback worked assert await MyObject.objects.acount() == 0 @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio class TestAsyncWithTransaction: async def test_1(self): # OK await MyObject.objects.acreate(name="same-name2") assert await MyObject.objects.acount() == 1 async def test_2(self): # OK # This should not see test_1's object if rollback worked assert … -
Displaying Categories using forloop in Django project not working
I am making an ecommerce website using Django, and for displaying categories as buttons in the navbar, I tried using a forloop, but its not working. {% for category in categorys %} <li class="nav-item"><a class="nav-link" href="#">{{ category.name }}</a></li> {% endfor %} I tried it with products and it worked. -
Docker django + host posfix gives `Bad destination mailbox address: Address not recognized by gateway`
I'm trying to persuade containerized django to send emails using the postfix installation on my host, and I'm told Bad destination mailbox address: Address not recognized by gateway. (For more detail, the django application I'm running is docker-zulip.) When I trigger a password-recovery email, I expect the email to be sent, but my server log in the container (/var/log/zulip/server.log) reports: 2025-09-01 22:47:00.280 ERR [zulip.send_email] Error sending password_reset email to ['User <user@gmail.com>' ]: {'User <user@gmail.com>': (550, b'5.1.1 Bad destination mailbox address: Address not recognized by gateway. ')} I'm aware of the SO post How do you configure Django to send mail through Postfix?, and I'm using its prescribed settings. But that post doesn't focus on docker setups, so it looks as if something further is required. Can the host send emails? Yes I can send emails from the host easily enough using echo "BODY" | mailx -r test@example.com -s "SUBJECT" user@gmail.com. Is postfix configured to recognize traffic from the container? I think so I've configured /etc/postfix/main.cf in a way that I think supports my docker container (running on 172.18.0.100): mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 172.18.0.0/24 inet_interfaces = 172.17.0.1 172.18.0.1 172.23.0.1 ...and I've run systemctl restart postfix. I don't see any activity … -
Nginx: “no ssl_certificate is defined for the listen … ssl directive” on custom port 8001
I’m running Django project behind Nginx on my VPS. Main project is at https://myproject.com (port 443) and works like a charm. I want to expose a second Django project at https://myproject.com:8001 but I couldn't load it on that address, I got the error mentioned in the title: no ssl_certificate is defined for the listen … ssl directive” on custom port 8001 For this, I updated /etc/nginx/sites-available/myproject to this (first part works fine for the main project at https://myproject.com, the second part is where I encounter some issues (marked with # NEW CONFIG FOR SECOND PROJECT (on :8001)): # Redirect all HTTP requests to HTTPS server { listen 80; server_name myproject.com www.myproject.com; return 301 https://$host$request_uri; } # Serve the app over HTTPS server { listen 443 ssl; server_name myproject.com www.myproject.com; ssl_certificate /etc/letsencrypt/live/myproject.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/myproject.com/privkey.pem; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/myname/myproject/staticfiles/; } location /media/ { alias /home/myname/myproject/media/; access_log off; expires 1h; } location / { include proxy_params; proxy_pass http://127.0.0.1:8000; } } ########################################## # NEW CONFIG FOR SECOND PROJECT (on :8001) # HTTP on :8001 → HTTPS on :8001 server { listen 8001; server_name myproject.com www.myproject.com; return 301 https://$host:8001$request_uri; } # HTTPS on :8001 for … -
How can I resolve this Django TemplateDoesNotExist error?
I'm working through the "Django 5 by Example" textbook, and am nearly finished with chapter 12, however at the very end when the text asks you to runserver and checkout http://127.0.0.1:8000/accounts/login, I get the following error: TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 5.2.5 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: C:\Users\Zergy\python\django\django-learning\env\educa\Lib\site-packages\django\template\loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: C:\Users\Zergy\python\django\django-learning\env\educa\Scripts\python.exe Python Version: 3.13.1 Python Path: ['C:\Users\Zergy\python\django\django-learning\educa', 'C:\Users\Zergy\AppData\Local\Programs\Python\Python313\python313.zip', 'C:\Users\Zergy\AppData\Local\Programs\Python\Python313\DLLs', 'C:\Users\Zergy\AppData\Local\Programs\Python\Python313\Lib', 'C:\Users\Zergy\AppData\Local\Programs\Python\Python313', 'C:\Users\Zergy\python\django\django-learning\env\educa', 'C:\Users\Zergy\python\django\django-learning\env\educa\Lib\site-packages'] Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Zergy\python\django\django-learning\env\educa\Lib\site-packages\django\contrib\admin\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Zergy\python\django\django-learning\env\educa\Lib\site-packages\django\contrib\auth\templates\registration\login.html (Source does not exist) I have checked, double-checked and triple-checked that my spelling and file structure are the same as what is given in the textbook, but the error persists. Here's the relevant parts of settings.py: INSTALLED_APPS = [ 'courses.apps.CoursesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ROOT_URLCONF = 'educa.urls' Here is the file structure Here is educa/urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('accounts/login/', auth_views.LoginView.as_view(), name='login'), path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT … -
I have a Django model called DataLog that stores API action logs. I need to delete this automatically after every 60 days
What is the best practice in Django to achieve this? Should I use a management command + cron job, django-crontab, or Celery beat for scheduling the deletion? Is there a way to make this automatic without having to call the cleanup manually inside my views? I tried using crontab by creating a function to delete the data after 60 days from created_at.