Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass env variables to django in production
I'm deploying a Django application using Gunicorn. In my Dev setup I used dotenv library to import environment variables in top my settings.py as follows: from dotenv import load_dotenv load_dotenv() I have two setting files; one is the base settings (settings.py) and the other file is the production one (settings_prod.py) that overrides some variables this way: from .settings import * DEBUG = False ALLOWED_HOSTS = [ 'subdomain.example.com', ] AUTH_PASSWORD_VALIDATORS = [ # ... ] STATIC_URL = os.environ.get('STATIC_URL', '/static/') STATIC_ROOT = os.environ.get('STATIC_ROOT', BASE_DIR / 'static') I'm loading this file in Gunicorn Service as follows: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=user Group=user-group WorkingDirectory=/home/myApp/core/app Environment="DJANGO_SETTINGS_MODULE=application.settings_prod" ExecStart=/home/myApp/core/app/venv/bin/gunicorn \ --log-level=debug \ --error-logfile /home/myApp/core/database/logs/gunicorn.errors.log \ --access-logfile /home/myApp/core/database/logs/gunicorn.log \ --workers 3 \ --bind unix:/run/gunicorn.sock \ application.wsgi:application [Install] WantedBy=multi-user.target I tried adding EnvironmentFile=/home/myApp/core/app/.env to the service file but it didn't help -
running django inside docker image : connection to server at "localhost" (127.0.0.1), port 5432 failed
I m new to docker. I ve downloaded a docker image at docker pull lambci/lambda:build-python3.8 which is a aws image to run lambda functions. I ve a Dockerfile that is : Dockerfile: FROM lambci/lambda:build-python3.8 WORKDIR /var/task EXPOSE 8000 RUN echo 'export PS1="\[\e[36m\]zappashell>\[\e[m\] "' >> /root/.bashrc CMD ["bash"] I've run docker build -t zappa-docker-image . docker run -ti -p 8000:8000 -e AWS_PROFILE=zappa -v "$(pwd):/var/task" -v ~/.aws/:/root/.aws --rm zappa-docker-image When I run django inside my docker image (python manage.py runserver), i get the following error: OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address Is the server running on that host and accepting TCP/IP connections? I guess it's related to postgresql in my django settings : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbtest', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': '5432', } } When I run the django server outside docker i dont get the error ... How can i solve this error in docker? -
How to check if URL is in Model/DB already on a URL Shortener? Django
i've been learning Django for these past days and i'm trying to develop an url shortener. It's functional and works great but it misses something: Check if the URL already exists so it can return the short URL stored in db. At this moments it's just checks if the short url is unique and does not exist already, so it always create a new and unique short url for the same URL. I've tried to use queryset's exists() in if ShortenerForm.objects.filter(url = cleaned_info['url']).exists(): but it always gave me an error object has no attribute 'cleaned_data' How can i do that? There are my files: views.py from django.http import Http404, HttpResponse, HttpResponseRedirect from django.shortcuts import render from utils.shorty.form import ShortenerForm from shorty.models import Shortener # Create your views here. def home(request): template = "shorty/pages/index.html" context = {} context["form"] = ShortenerForm() if request.method == "GET": return render(request, template, context) elif request.method == "POST": used_form = ShortenerForm(request.POST) if used_form.is_valid(): shortened_object = used_form.save() new_url = request.build_absolute_uri("/") + shortened_object.shortcode long_url = shortened_object.url context["new_url"] = new_url context["long_url"] = long_url return render(request, template, context) context["errors"] = used_form.errors return render(request, "shorty/pages/index.html") def redirect_url_view(request, shortened_path): try: shortener = Shortener.objects.get(shortcode=shortened_path) shortener.redirectCount += 1 shortener.save() return HttpResponseRedirect(shortener.url) except: raise Http404("Sorry this … -
Can I use python fastapi for large and complex web development project?
I am an django developer. Now I want to move fastapi but I am not fully confident. I have few question. question 1: Can fast api handle huge number of visitor like django? question 2: How strong fast api security level if we compare it with django? does it provide same level of security like django? Django provide security against sql injection, cross site scripting etc. question 3 Does fastapi scalable like django? question 4 Can we use fast api for build complex website where we have to do lot of background task? question 5 How fastapi user authentication work? is it similar to django? question 6 if you move to fastapi web framework? then what was the main reason for moving fastapi? which feature do you like most of fastapi? question 7 How big is fastapi community? is it large community like django? -
How can I post a variable from a python file to an html file in Django?
I am trying to make a face recognition page using PyTorch. When the face is recognized, I want to go to the next page and print the name of the recognized person. I wrote the code, but on the next page, None is printed. In my terminal, "POST / HTTP/1.1" 200 532 is printed repeatedly sometimes "GET /page HTTP/1.1" 200 308 is printed. That is, I want to output the name and min_dist from the get_frame of camera2.py in the page.html file. (camera2.py) name, min_dist ---post---> (page.html) name, min_dist urls.py from . import views urlpatterns = [ path('', views.home, name='home'), path('detectme', views.detectme, name='detectme'), path('page', views.get_post, name='page') ] views.py from django.shortcuts import render from django.views.decorators import gzip from django.http import StreamingHttpResponse from detectme.camera2 import FaceDetect def home(request): return render(request, 'home.html') def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def detectme(request): return StreamingHttpResponse(gen(FaceDetect()), content_type="multipart/x-mixed-replace;boundary=frame") def check(request): return render(request, "page.html") def get_post(request): if request.method == 'POST': student = request.POST.get('student') pred = request.POST.get('pred') data = { 'name' : student, 'pred' : pred } return render(request, 'page.html', data) if request.method == 'GET': student = request.POST.get('student') pred = request.POST.get('pred') data = { 'name' : student, 'pred' : pred } … -
Django with mysql database always return (2013, 'Lost connection to MySQL server during query')
I have a django app that was working perfectly until today. It is connected to a mysql database I was doing some tests in the python console and it started giving me the error (2013, 'Lost connection to MySQL server during query'). The problem now is that I have no way to access the application. It always returns the same error. It is very rare because it has started to happen suddenly. I've searched the stackoverflow questions but haven't been able to figure it out or find the error. This is error: The above exception ((2013, 'Lost connection to MySQL server during query')) was the direct cause of the following exception: File "/var/www/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/var/www/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 202, in _get_response response = response.render() File "/var/www/env/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/var/www/env/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/var/www/env/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/var/www/env/lib/python3.8/site-packages/django/template/base.py", line 170, in render return self._render(context) File "/var/www/env/lib/python3.8/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/var/www/env/lib/python3.8/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/var/www/env/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/var/www/env/lib/python3.8/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/var/www/env/lib/python3.8/site-packages/django/template/base.py", line 162, … -
Audio cannot pass from model to template - DJANGO
i want to pass audio file to template html from url. but when i add source, the audio controls doesn't work. i was copy how to pass audio file, but i don't know where's wrong. so please help me to fix this. at my terminal and console, there's no error message. here's my html : {% for record in rec %} <audio controls> <source src=" {% if record.audio %} {{ record.audio.url }} {% endif %}" type="audio/mp3"> </audio> {% endfor %} views.py : def mp3_audio(request): rec = Audio_store.objects.all() return render(request, 'homepage.html' , {'rec': rec }) urls.py : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), url(r'^$', views.homepage), path('audio', views.Audio_store), path("", views.homepage, name="homepage"), ] models.py : from django.db import models from django.core.files.storage import FileSystemStorage from django.forms import widgets fs = FileSystemStorage(location='media/mp3') fss = FileSystemStorage(location='media/txt') class Audio_store(models.Model): password=models.FileField(storage=fss, null=True) audio=models.FileField(storage=fs, null=True) -
How to get image from django inline ModelAdmin
I have such structure models.py: class Image(models.Model): article = models.ForeignKey('article', on_delete=models.CASCADE, null = True) image = models.ImageField(upload_to = "images/") class Article(models.Model): title = models.CharField(max_length = 255) admin.py: class ImageInline(admin.StackedInline): model = Image class ArticleAdmin(admin.ModelAdmin): inlines = [ ImageInline, ] How can I get images from ImageInline in ArticleAdmin for further use in template? P.S. I need these images to create a slider -
Django signal - Not Triggered
Hi all I am using the Django request_started signal to log django request from django.core.signals import request_started from django.dispatch import receiver logger = logging.getLogger(__name__) @receiver(request_started) def log_request(sender, environ, **kwargs): method = environ['REQUEST_METHOD'] path = environ['PATH_INFO'] logger.info(f"{method} {path}") but Diango signals are not logged -
How to display items individually django/javascript
So I'm coding a quiz app in django and I want to display the questions individually and once the user seleect an answer and click Next the next question will be displayed how can I do this models.py: class Question(models.Model): text = models.CharField(max_length=200) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.text) def get_answers(self): ''' Get the set of all the answers to the questions ''' return self.answer_set.all() class Answer(models.Model): text = models.CharField(max_length=200) correct = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"question: {self.question.text}, answer: {self.text}, correct: {self.correct}" -
Django model, integers as choices
could you tell me if the following code is correct? I want to create a drop down that in the django admin will show a dropdown with a selection of integer: class Test(TimeStampedModel): """ Test specifications """ TIME_INTERVALS = Choices( ('SECONDS_30', 30) ('SECONDS_60', 60) ('SECONDS_90', 90) ('SECONDS_120', 120) ('SECONDS_150', 150) ('SECONDS_300', 300) ) sample_time = models.PositiveSmallIntegerField(choices=TIME_INTERVALS, default=TIME_INTERVALS.SECONDS_30) Thank you -
Django REST Framework how to output a cropped copy of an image in the serializer?
I have a question when working with images. I've overridden the save method in models, in order to save multiple versions of images. Now I want to use a second resized saved version of the image in the Serializer. Please advise how I can do this and is such a scenario possible? def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image) thumbnail_size = (500, 500) img.thumbnail(thumbnail_size) image_name, image_ext = os.path.splitext(self.image.path) custom_path1 = '{}_500{}'.format(image_name, image_ext) img.save(custom_path1, "JPEG", optimize=True, quality=75) -
Why create() method not being called in ViewSet when using "raw data"?
I'm having some trouble to identify what's wrong; I have an API that receives a POST with some information: then they are used as params to run some code and save an image. So far, all things were working correctly until I stumbled across this: When I use the "HTML Form" the 'create()' method in my 'views.py' works fine, but when I use the 'Raw Data' it also works but it don't trigger the 'create()' method in my ViewSet... Any idea on why is this happening? And, if I need to only use the 'HTML Form', how other services may post to my API in order to it runs the code accordinly? Here are my: models.py usuario = models.CharField(max_length=50) codigo = models.CharField(max_length=30) ambiente = models.CharField(max_length=30) itens = models.CharField(max_length=10000) imagem = models.ImageField(default='placeholder.jpg') def __str__(self): return self.codigo def nome_imagem(self): self.imagem = self.codigo + "_" + self.usuario + "_" + self.ambiente + ".jpg" def save(self, *args, **kwargs): self.nome_imagem() return super(Imagem, self).save(*args, **kwargs) serializer.py class Meta: model = Imagem fields = ['id','usuario','codigo','ambiente','itens','imagem'] views.py class ImagemViewSet(viewsets.ModelViewSet): queryset = Imagem.objects.all() serializer_class = ImagemSerializer def create(self, request, *args, **kwargs): informacao = request.data msglist = [] try: for value in informacao.values(): msglist.append(value) codigo = msglist[2] usuario = msglist[1] … -
I can't save Many to Many with through model, using ModelMultipleChoiceField
I'm stuck trying save many to many relationship through custom model, using ModelMultipleChoiceField. Django shows this error: Cannot assign "<QuerySet [<Project: MARKETING 7>]>": "ProjectEmployee.project" must be a "Project" instance. I can't find solution for this. models.py class Department(models.Model): name = models.CharField('Name', max_length=200, unique=True) class Employee(models.Model): department = models.ManyToManyField(Department, through='DepartmentEmployee') name = models.CharField('Name', max_length=200, unique=True) lastname = models.CharField('Last Name', max_length=200, unique=True) class DepartmentEmployee(models.Model): department = models.ForeignKey(Department, on_delete=models.PROTECT) employee = models.ForeignKey(Employee, on_delete=models.PROTECT) date_joined = models.DateField() forms.py class ProjectEmployeeForm(forms.ModelForm): project = forms.ModelMultipleChoiceField( required=True, queryset=Project.objects.all(), ) class Meta: model = ProjectEmployee fields = '__all__' views.py def project_employee(request, id): employee = get_object_or_404(Employee, id = id) if request.method == 'POST': form = ProjectEmployeeForm( request.POST or None, ) if form.is_valid(): f = form.save(commit=False) f.employee = employee f.save() redirect('employe:list') else: form = ProjectEmployeeForm() template = 'prject_employee.html' context = { 'form': form, } return render(request, template, context) urls.py path('<int:id>/project_employee/', project_employee, name='project_employee'), -
Displaying Image in Django
I have the following code which is suppose to print an image. from email.mime import image from django.http import HttpResponse import datetime from django.template.loader import render_to_string import base64 import math import random import matplotlib.pyplot as plt no_of_balls = 25 x = [random.triangular() for i in range(no_of_balls)] y = [random.gauss(0.5, 0.25) for i in range(no_of_balls)] colors = [random.randint(1, 4) for i in range(no_of_balls)] areas = [math.pi * random.randint(5, 15)**2 for i in range(no_of_balls)] plt.figure() plt.scatter(x, y, s=areas, c=colors, alpha=0.85) plt.axis([0.0, 1.0, 0.0, 1.0]) plt.xlabel("X") plt.ylabel("Y") plt.savefig('test.png') # with open("test.png", "rb") as image: # b64string = base64.b64encode(image.read()) def math_is_fun(request): now = datetime.datetime.now() with open("test.png", "rb") as image: b64string = base64.b64encode(image.read()) with open('encode.bin', "wb") as file: file.write(b64string) # file = open('encode.bin', 'rb') # byte = file.read() # file.close() # decodeit = open('test.png', 'wb') # decodeit.write(base64.b64decode((byte))) # decodeit.close() context = { 'time' : now, 'image' : decodeit, } HTML_STRING = render_to_string("home-view.html", context = context) return HttpResponse(HTML_STRING) Just some background. What I had done is created an image from some math formula and saved it to disk. Then since I am using render_to_string in django views, I assumed that the image has to be converted to string. Which I did using base64. I am having … -
How can i deploy nuxt app to django server
I wonder If there is any way to deploy a nuxt js app on a django server Is there any way like a template engine or similar solutions for doing this ? To be exact and short I want to use only one server for my website -
Celery / Celery beat stuck on old version of a script
I've got a django application running on AWS EC2 using Celery for periodic updates. I recently had to update a data processing script on the Django app, but no matter what I seem to try, Celery continues to use old copies of the processing script. Here's a run down: There was a change in how the data was published starting April 12. So the old processor stopped working on any data after April 12. I amended the script to work on all the data both up to and after April 12 and merged the changes to production. GitHub Actions ran successfully, built the containers, and deployed them to EC2. If I ssh into the EC2 instance and enter the container, I can run the manage.py update_nameofmydatamodel command and it runs properly and updates all of the data properly (I can tell because this feeds a website viz that then properly updates) When Celery Beat runs overnight, the data reverts to processing ONLY up to April 12 (I can tell because I go to the website viz and it has reverted back to only having data up to April 12) I removed the data model from the list of models to … -
createsuperuser works, but createuser does not
When i try to create a new user using my api, Django is not executing the create_user function and password is not hashed. When i createsuperuser in the terminal user password is hashed and create_superuser is executed(its using the previous create_user func). Could you please help? Thank you. class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, name, password): """Create a new user profile""" if not email: raise ValueError('Users must have an email adress!') email = self.normalize_email(email) user = self.model(email=email, name=name) import pdb;pdb.set_trace() user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): """Create and save a new superuser with given credentials""" user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user -
What is the difference between "database backend" and "database bindings" in Python?
The Django tutorial over at djangoproject.com uses both terms, databse backend, and database bindings. What is the difference? Judging by semantics, I would've guessed a database "backend" to be some reside-on-the-server thing .., and "bindings" to denote configuations..? For example, which does cx_Oracle identify with? -
Forbidden: /api/v1.0/user/create-user/ & { "detail": "Authentication credentials were not provided." } DJANGO
I was creating Login functionality for my Python Django backend, "create user" functionality was working fine before. But then after Login was entirely coded, the create-user stopped working. My urls.py file: from django.urls import path from .views import TestView, UserView, UserLoginView from rest_framework_jwt.views import refresh_jwt_token, verify_jwt_token urlpatterns = [ path('test', TestView.as_view()), path('create-user/', UserView.as_view()), path('get-user', UserLoginView.as_view()), path('login-user/', UserLoginView.as_view()), ] My views.py file: from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer from django.contrib.auth.models import User from django.contrib.auth import authenticate class TestView(APIView): def get(self, request, format=None): print("API called") return Response("You did it!", status=200) class UserView(APIView): def post(self, request, format=None): print("Creating User") user_data = request.data print(request.data) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(raise_exception=False): user_serializer.save() return Response({'user': user_serializer.data}, status=200) return Response({'msg': "error: no user created"}, status=400) class UserLoginView(APIView): # convert user token to user data def get(self, request, format=None): if request.user.is_authenticated == False or request.user.is_active == False: return Response('Invalid credentials', status=403) user = UserSerializer(request.user) print(user.data) return Response("Testing", status=200) def post(self, request, format=None): print("Login class") # Looking for user's email or username user_obj = User.objects.filter(email=request.data['email']).first( ) or User.objects.filter(username=request.data['username']).first() # if user is valid, returns user data in credentials if user_obj is not None: credentials = { 'username': user_obj.username, 'password': request.data['password'] } user = authenticate(**credentials) … -
DRF to select only some values from ForeignKey - Django
I am using Django Rest Framework and I am new to DRF. serializer.py class ResponseSerializer(serializers.ModelSerializer): class Meta: model = Response fields = [ 'user_id', 'question_id', ] As you can see I have 2 fields here user_id question_id Both of them are foreign key fields When someone hits this url http://127.0.0.1:8000/api/response/add/, they can see all the values when they select user_id or question_id. urls.py path('api/response/add/', views.response_create_view), And this is my views.py class ResponseCreateAPIView(generics.CreateAPIView): serializer_class = ResponseSerializer authentication_classes = [authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticated] response_create_view = ResponseCreateAPIView.as_view() What I want is user_id should only have 1 value in list and that is current user. question_id should have only those questions which I have filtered For instance, I only want these questions only queryset = Question.objects.filter(publish=True) Whats the best way I can achieve this? Thanks in advance !! Django Version: 3.2.12 -
Django Materialize Multiple Dropdowns
This might be pretty extensive - so any help is greatly appreciated. Similar: Materialize CSS (with django) dropdown form not working How to Implement 3-way Dependent/Chained Dropdown List with Django? I am working on a project involving dependent drop down menus following this django tutorial. Only difference is I am working with materialize css/js. The problem is that the drop-downs are not populating, and populate only after I post the form - Pre-"post", and Post-"post". When I do not initiate materialize - the form works. Materialize css/js is still a need though as it maintains consistency between my other pages. Even after I have initialized the 'select' after the materialize js was loaded: (Materialize docs here) HTMLs Base.html <head> {% load static %} <!-- Prism CSS --> <link href="{% static "tinymce/css/prism.css" %}" rel="stylesheet"> <!-- Compiled and minified JavaScript --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script> {% comment %} $(document).ready(function(){ $('select').formSelect(); }); {% endcomment %} document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('select'); var instances = M.FormSelect.init(elems); }); </script> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="{% static "main/css/materialize.css" %}"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <nav> <div class="nav-wrapper" <ul id="nav-mobile" class="right hide-on-med-and-down"> {% include 'main/includes/navbar.html' %} </ul> </div> </nav> {% include 'main/includes/messages.html' … -
cannot migrate from Django sqlite3 to postgres, getting "psycopg2.errors.UndefinedTable: relation doest not exist" error
I am trying to migrate the sqlite3 db from my Django app to postgres db. I have tried all the tutorials out there but cant seem to solve this error when I try to run 'python manage.py migrate --run-syncdb' or 'python manage.py migrate'. I have installed psycopg2 as well. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432', } } The error is "psycopg2.errors.UndefinedTable: relation "users_postcategory" does not exist LINE 1: ...ategory"."name", "users_postcategory"."name" FROM "users_pos..." screenshot1 screenshot2 -
(Django/Python) Error while deploying "chrnorm/deployment-action"
On GitHub I am trying to deploy a project to Herokuapp and I got this error during the "Create GitHub Deployment" stage of Deployment: Run chrnorm/deployment-action@releases/v1 with: initial_status: success token: *** target_url: https://***.herokuapp.com environment: production env: HEROKU_API_KEY: *** HEROKU_APP_NAME: *** Error: HttpError: Resource not accessible by integration Error: Resource not accessible by integration Here are the requirements.txt coverage>=5.3,<6.0 dj-database-url>=0.5.0 Django>=3.1.0,<4.0.0 gunicorn>=20.0.0,<21.0.0 psycopg2-binary>=2.8.0,<3.0.0 selenium>=3.141.0,<4.0.0 whitenoise>=5.2.0,<6.0.0 Can anyone please tell me what's wrong? Thank youuu -
Python Flask Caching 401 POST and Applying to next request
I have a Python flask backend that returns JSON. Every time I make a POST request that returns a 401 (because tokens have expired) it then prepends the JSON body data to the next request, which causes a 405 method not allowed because as you can see, the data is showing where the method should be. This is the same issue as this post for Django This is the log from my local: 127.0.0.1 - - [25/May/2022 08:17:01] "POST /stsatellites/filter HTTP/1.1" 401 - 127.0.0.1 - - [25/May/2022 08:17:29] "OPTIONS /auth/login HTTP/1.1" 200 - 127.0.0.1 - - [25/May/2022 08:17:29] "{"filters":[{"field":"NORAD_CAT_ID","op":"eq","value":25165}]}POST /auth/login HTTP/1.1" 405 - Here are screenshots of the requests, as you can see that filter data originated on the first request which got the 401 response. Filter POST Filter POST Payload Following Login request: Login POST Headers Login POST Payload We have a workaround in place which resolves this issue but it's a band-aid that I would like to remove. For some reason the request.get_data method fixes the caching issue. @app.after_request def after_request_func(response): if response.status == "401 UNAUTHORIZED": request.get_data(cache=False) return response