Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Building development image with Nodejs and production without NodeJS (with only precompiled files)
I have a Django application, which is using TailwindCSS for styling (using the django-tailwind package). I am developing locally with docker compose and plan to deploy using the same. So I have the following requirements For development: I need to run the python manage.py tailwind start or npm run dev command so that the postcss watcher rebuilds the static files when I am developing the application (this requires NodeJS) For Production: I compile the CSS files at build time and do not need NodeJS overhead. I can always create two Dockerfiles for development and production, but I do not want to do that unless absolutely necessary. How can I do both of these in a single Dockerfile. This is the current Dockerfile I have ARG BUILD_TYPE=production FROM ghcr.io/astral-sh/uv:python3.13-bookworm-slim AS base-builder # Set environment variables to optimize Python ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # Set environment variables to optimize UV ENV UV_COMPILE_BYTECODE=1 ENV UV_SYSTEM_PYTHON=1 WORKDIR /app # Install the requirements COPY uv.lock . COPY pyproject.toml . # Update the package list and install Node.js RUN apt-get update && \ apt-get install -y nodejs npm && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* FROM base-builder AS production-builder RUN echo "Running the Production … -
dj-rest-auth + allauth not sending email
Context: I'm setting DRF + dj-rest-auth + allauth + simple-jwt for user authentication. Desired behaviour: Register with no username, only email. Authorize login only if email is verified with a link sent to email. Social login to be added. Problem: It seems that confirmation email is not being sent. When I run the following test I see that it wanted to send some email but it's not found anywhere. Test code: client = APIClient() url = reverse("rest_register") # dj-rest-auth register endpoint # Register a user data = { "email": "user1@example.com", "password1": "StrongPass123!", "password2": "StrongPass123!", } response = client.post(url, data, format="json") assert response.status_code == 201, response.data print(response.data) # Manually verify the user from allauth.account.models import EmailConfirmation user = User.objects.get(email="user1@example.com") from django.core import mail print(f'Amount of sent emails: {len(mail.outbox)}') print(f'Email Confimation exists: {EmailConfirmation.objects.filter(email_address__email=user.email).exists()}') This prints: {'detail': 'Verification e-mail sent.'} Amount of sent emails: 0 Email Confimation exists: False My code: core/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('api/auth/', include('authentication.urls')), path("admin/", admin.site.urls), path("accounts/", include("allauth.urls")), ] authentication/urls.py from dj_rest_auth.jwt_auth import get_refresh_view from dj_rest_auth.registration.views import RegisterView, VerifyEmailView from dj_rest_auth.views import LoginView, LogoutView, UserDetailsView from django.urls import path from rest_framework_simplejwt.views import TokenVerifyView urlpatterns = [ path("register/", RegisterView.as_view(), name="rest_register"), path("register/verify-email/", VerifyEmailView.as_view(), … -
Celery task called inside another task always goes to default queue even with queue specified
I’m running Celery with Django and Celery Beat. Celery Beat triggers an outer task every 30 minutes, and inside that task I enqueue another task per item. Both tasks are decorated to use the same custom queue, but the inner task still lands in the default queue. from celery import shared_task from django.db import transaction @shared_task(queue="outer_queue") def sync_all_items(): """ This outer task is triggered by Celery Beat every 30 minutes. It scans the DB for outdated items and enqueues a per-item task. """ items = Item.objects.find_outdated_items() for item in items: # I expect this to enqueue on outer_queue as well process_item.apply_async_on_commit(args=(item.pk,)) @shared_task(queue="outer_queue") def process_item(item_id): do_some_processing(item_id=item_id) Celery beat config: CELERY_BEAT_SCHEDULE = { "sync_all_items": { "task": "myapp.tasks.sync_all_items", "schedule": crontab(minute="*/30"), # Beat is explicitly sending the outer task to outer_queue "options": {"queue": "outer_queue"}, } } But, when I run the process_item task manually e.g. in the Django view, it respect the decorator and lands in expected queue. I’ve tried: Adding queue='outer_queue' to apply_async_on_commit Calling process_item.delay(item.pk) instead Using .apply_async(args=[item.pk], queue='outer_queue') inside transaction.on_commit But no matter what, the inner tasks still show up in the default queue. -
Django + SimpleJWT: Access tokens sometimes expire immediately ("credentials not provided") when calling multiple endpoints
I’m building a Vue 3 frontend (deployed on Vercel at example.com) with a Django REST Framework backend (deployed on Railway at api.example.com). Authentication uses JWT access/refresh tokens stored in HttpOnly cookies (access, refresh). Access token lifetime = 30 minutes Refresh token lifetime = 1 day Cookies are set with: HttpOnly; Secure; SameSite=None; Domain=.example.com Django timezone settings: LANGUAGE_CODE = "en-us" TIME_ZONE = "Africa/Lagos" USE_I18N = True USE_TZ = True The problem When the frontend calls multiple API endpoints simultaneously (e.g. 5 requests fired together), some succeed but others fail with: 401 Unauthorized {"detail":"Authentication credentials were not provided."} In the failing requests I can see the cookies are sent: cookie: access=...; refresh=... But SimpleJWT still rejects the access token, sometimes immediately after login. It looks like the exp claim in the access token is already in the past when Django validates it. What I’ve tried Verified cookies are set with correct domain and withCredentials: true. Implemented an Axios response interceptor with refresh token retry. Ensured CookieJWTAuthentication checks both Authorization header and access cookie. -
"Django: Cannot use ImageField because Pillow is not installed (Python 3.13, Windows)
PS C:\Users\ltaye\ecommerce> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ltaye\AppData\Local\Programs\Python\Python313\Lib\threading.py", line 1043, in _bootstrap_inner self.run() ~~~~~~~~^^ File "C:\Users\ltaye\AppData\Local\Programs\Python\Python313\Lib\threading.py", line 994, in run self._target(*self._args, **self._kwargs) ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ltaye\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) ~~^^^^^^^^^^^^^^^^^ File "C:\Users\ltaye\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(**check_kwargs) ~~~~~~~~~~^^^^^^^^^^^^^^^^ File "C:\Users\ltaye\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\core\management\base.py", line 569, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: store.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". System check identified 1 issue (0 silenced). I created a Django project and added a model with an ImageField. When I run python manage.py runserver, I get the following error: SystemCheckError: Cannot use ImageField because Pillow is not installed. I expected the server to start normally and let me upload images. I already tried: Running python -m pip install Pillow Running pip install Pillow inside my project virtual environment Upgrading pip with python -m pip install --upgrade pip But the error still shows up when I start the server. I’m using Python 3.13 on Windows 11. -
How to write a documentation for project/django-project?
How do you write documentation for your projects? How to improve readability of documentation? Do you have any tips for writing documentation? Thanks! Im trying to write my first documenation for django API project and I need a help -
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!