Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript Counting Occurrences Based on Django For Loop
Hi I was wondering if someone could help me figure out how to count the number of occurrences of a word in a django array. For instance, this array currently returns [Train, Car, Car, Train, Motorcycle, Plane]. I want it to return that Train appears 3 times, Car 2 times, etc. If anyone can help it would be greatly appreciated! Thanks. <script> let distribution = document.querySelectorAll(`[id^="distribution"]`) const shipment = Array.from(document.querySelectorAll('.method-of-shipment')); const shipment_inner = shipment.map((element) => element.innerText); function countOccurrences(str,word) { // split the string by spaces in a let a = str.split(","); // search for pattern in a let count = 0; for (let i = 0; i < a.length; i++) { // if match found increase count if (word==(a[i])) count++; } return count; } // Driver code let str = shipment_inner; let word = "Train"; distribution.innerText = document.write(countOccurrences(str, word)); </script> <div> {% for loans in loans_in_securities %} <a class="method-of-shipment">{{loans.method_of_shipment}}</a> {% endfor %} <br> <a id="distribution"></a> </div> -
How to save formsets in django
I want to add multiple forms when a button is clicked and I am using formsets to accomplish that but when I try to save the forms it doesn't give an error bu does not save it either. my views.py: def StepThreeView(request): formSet = modelformset_factory(Club, fields=("name", "channel", "logo", "created_by")) form = formSet(queryset=Example.objects.none()) if (request.method == "POST"): form = formSet(request.POST) if (form.is_valid()): form.save() context = { 'form': form } return render(request, 'on_boarding/step_three.html', context) my html: <form method="POST" id="form"> {% csrf_token %} {{ form.management_form }} <div class="hidden" id="form-copy"> {{ form.empty_form.as_p }} </div> </form> <button class="add-club" type="button" onclick="AddUser()"> Add user </button> my javascript: function AddUser() { const formCopyTarget = document.getElementById("formCopyTarget"); const copyForm = document.getElementById("form-copy").cloneNode(true) const totalNewForm = document.getElementById('id_form-TOTAL_FORMS') const currentForms = document.getElementsByClassName("block") let totalForms = currentForms.length copyForm.setAttribute('class', 'block') copyForm.setAttribute('id', `form-${totalForms}`) const regex = new RegExp('__prefix__', 'g') copyForm.innerHTML = copyForm.innerHTML.replace(regex) totalNewForm.setAttribute('value', totalForms + 1) formCopyTarget.append(copyForm) } -
How to show choices fields in django admin?
I have a model with a lot of fields, Some fields are Char type with choices https://docs.djangoproject.com/en/dev/ref/models/fields/#choices These fields don't display in the admin panel list_display I generate like this list_display = [field.name for field in Event._meta.get_fields()] How to change the generation of the list, so that fields with type choices are shown ? Thanks in advance -
How can I count overall how many reviews are in an author's all posts?
I building an e-Commerce website, here also has a system of merchandiser accounts. Every merchandiser can upload their product photo with all information for selling. A merchandiser can sell different types of products. Buyers can give product reviews on the product they bought. Now I want to show the overall total of how many buyers have given feedback on seller products. For example: seller-1: 10 reviews, 4.5 star, seller-2: 5 reviews, 4.8 star, seller-3: 11 reviews, 4.1 star. How can I do it? Please help me😢... models.py: class Products(models.Model): user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True) product_title = models.CharField(blank=True, null=True, max_length = 250) brand = models.CharField(max_length=250, blank=True, null=True) product_desc = RichTextField(blank=True, null=True) class ProductREVIEWS(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userREVIEW',on_delete=models.CASCADE) product = models.ForeignKey(Products, related_name='productREVIEWrelatedNAME',on_delete=models.CASCADE) feedBACK = models.TextField(blank=True, null=True) rating = models.IntegerField(blank=True, null=True) -
How to establish a tcp connection through a proxy ip in python?
I need to connect to a server that periodically sends text data over a TCP connection, and the server needs my IP to be static. My backend (Django) is hosted on Heroku (dynamic IPs), but I have an add-on service that provides me with the static IPs (whitelisted by the target server). How do I route the TCP connection through a proxy IP? -
Select 2 query and Bootstrap 5
para las model de boostrap 5 se debe agragar las siguientes lineas para que funcione correctamente : jQuery(document).ready(function($){ $(document).ready(function() { $('#id_select').select2({ width: '100%', dropdownParent: $('.modal-body','#mymodel') }); }); }); -
How to render my function in html in Django
please excuse me in advance in case that my question has been answered many times before. Cause I'm new to django, I just don't have a clue which keyword I have to search with. I made a countdown timer which works well in the console. The function display a clock(remaining days:hours:mins:secs) decrementing a sec until the end. def countdown(): dt = get_delta() while dt > 0: d = calculation(dt)['day'] h = calculation(dt)['hour'] m = calculation(dt)['min'] s = calculation(dt)['sec'] countdown.timer = '{:02d} days {:02d} hours {:02d} mins {:02d} secs'.format(d, h, m, s) print(countdown.timer, end='\r') time.sleep(1) dt -= 1 countdown.boom = "--------Happy birthday!--------" print(countdown.boom) What I want to do is to render this part on my webpage built by django. countdown.timer = '{:02d} days {:02d} hours {:02d} mins {:02d} secs'.format(d, h, m, s) This is my render function part: def index(request): context = {'timer': countdown.timer} return render(request, 'MainApp/index.html', context) I tried to pass countdown.timer variable or countdown() function itself to my django template. <div class="container-fluid" style="background-color: black"> <div class="rows"> <div class="col-md-12"> <article> <h1>This is where my timer is.</h1> <p>{{ timer }}</p> </article> </div> </div> </div> It doesn't feel right and it didn't work but I don't know how to get it done. … -
Django-compressor not finding blocks to compress in a GitHub Action
I have a Django project that's using django-compressor to minify and concatenate CSS files, using offline compression. I haven't yet put it on a server, but when I run manage.py compress in a GitHub Action, before running tests, it can't find the {% compress %} block, even though it can find the template containing them. I have a single template that uses CSS files, templates/myapp/layouts/base.html: <!DOCTYPE html> {% load compress static %} <html lang="en"> <head> <!-- ... --> {% compress css file global %} <link rel="stylesheet" href="{% static 'oohdir/css/global/variables.css' %}"> <link rel="stylesheet" href="{% static 'oohdir/css/global/reset.css' %}"> <link rel="stylesheet" href="{% static 'oohdir/css/global/form.css' %}"> <!-- etc --> {% endcompress %} When running the site locally I can have these Django settings: DEBUG = False COMPRESS_ENABLED = True COMPRESS_OFFLINE = True and when I run manage.py compress it generates a single CSS file, as expected, in static_collected/CACHE/CSS/. That file is linked in the HTML when I view pages in the browser (using manage.py runserver --insecure). But when I run my GitHub Action many tests fail because of a missing file, which django-compressor didn't generate. If I run manage.py compress --verbosity 2 in the Action I can see it finds the correct template among … -
Django: problem trying to post data to django model database
ProgrammingError at /admin/formRegister/formregister/ column formRegister_formregister.password1 does not exist LINE 1: ...astname", "formRegister_formregister"."username", "formRegis... ^ Request Method: GET Request URL: http://localhost:8000/admin/formRegister/formregister/ Django Version: 4.0.5 Exception Type: ProgrammingError Exception Value: column formRegister_formregister.password1 does not exist LINE 1: ...astname", "formRegister_formregister"."username", "formRegis... ^ Exception Location: C:\Users\hp\Desktop\Django\django3.9\lib\site-packages\django\db\backends\utils.py, line 89, in _execute Python Executable: C:\Users\hp\Desktop\Django\django3.9\Scripts\python.exe Python Version: 3.9.13 Python Path: ['C:\Users\hp\Desktop\Django\teluskoa', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\python39.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\hp\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\Users\hp\Desktop\Django\django3.9', 'C:\Users\hp\Desktop\Django\django3.9\lib\site-packages'] Server time: Thu, 11 Aug 2022 16:02:26 +0000 -
resource objects need to have a primary key value before you can access their tags
I am using django-taggit. When i used pre-save signal then I got the error below. resource objects need to have a primary key value before you can access their tags. model.py class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) varient=models.CharField(max_length=100, default="") Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(default="", unique=True, blank=True) Tags = TaggableManager(blank=True) pre-save signal function is def tag_set(sender, instance, **kwargs): print(instance.Tags) pre_save.connect(tag_set, sender=resource) -
Django prefetch_related multiple fields
Let's assume I have the following model class Store: name = models.CharField() location = models.CharField() clients = models.ManyToManyField('Client', related_name='stores', on_delete=models.CASCADE) providers = models.ManyToManyField('Provider', related_name='stores', on_delete=models.CASCADE) rating = models.CharField(max_length=128, choices=Rating.choices(), blank=True) I am aware I can do something like Store.objects.all().prefetch_related('clients') to prefetch the clients; however, I need to prefetch for providers as well, I could write to different queries, but I am wondering if I can something like Store.objects.all().prefetch_related('clients', 'providers') Additionally, what would be the best way to group them by rating? There might be betters way to this, any feedback is more than welcome. Thank you all!! -
I am getting this error in context_processors 'NoneType' object is not iterable
I want to show messages in every template that's why I need a context processor. But I am getting this error 'NoneType' object is not iterable. I can not resolve this problem. Can anyone see the code and give a solution for it. # context_processors.py from django.contrib import messages from .models import Loan def message_notification(request): loan_requested_lists = Loan.objects.filter(loan_req_user=request.user, active=True, status='Pending') if loan_requested_lists.exists(): if loan_requested_lists.count() == 1: for i in loan_requested_lists: return messages.info(request, f'{i.user.username}({i.user.account_number}) was requested for loan.') else: return messages.info(request, f'{loan_requested_lists.count()} users were requested for loan.') This is my models.py from django.utils import timezone from django.db import models from accounts.models import User from django.core.exceptions import ValidationError # Create your models here. STATUS = ( ('Pending', 'Pending'), ('Accepted', 'Accepted') ) EDITABLE_STATUS = ( ('Not Applicable', 'Not Applicable'), ('Requested', 'Requested'), ('Approved', 'Approved'), ('Not Approved', 'Not Approved'), ('Updated', 'Updated'), ) def validate_date(date): if date < timezone.now(): raise ValidationError("Date cannot be in the past") class Loan(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) loan_req_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='loan_given_user_list', verbose_name='Loan Requested From User') amount = models.PositiveIntegerField(verbose_name='Loan Amount') date = models.DateTimeField(default=timezone.now, validators=[validate_date], verbose_name='Loan Return Date') status = models.CharField(max_length=8, choices=STATUS, default='Pending') editable = models.CharField(max_length=14, choices=EDITABLE_STATUS, default='Not Applicable') active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True, verbose_name='Loan Requested Date') def __str__(self): return self.user.username -
Send email with attach in python error under https
i have an error trying to send email with attach pdf in python (Django) under https active but not do under http, this is my code: from django.conf import settings import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders sender_email_address = sender@mail.com email_password = myPass email_smtp = smtp.gmail.com email_subject = self.titulo receiver_email_address = receiver@gmail.com remitente = sender_email_address destinatarios = [receiver_email_address] asunto = email_subject cuerpo = self.cuerpo ruta_adjunto = 'file.pdf' nombre_adjunto = 'file.pdf' mensaje = MIMEMultipart() mensaje['From'] = remitente mensaje['To'] = ", ".join(destinatarios) mensaje['Subject'] = asunto mensaje.attach(MIMEText(cuerpo, 'plain')) archivo_adjunto = open(ruta_adjunto, 'rb') adjunto_MIME = MIMEBase('application', 'octet-stream') adjunto_MIME.set_payload((archivo_adjunto).read()) encoders.encode_base64(adjunto_MIME) adjunto_MIME.add_header('Content-Disposition', "attachment; filename= %s" % nombre_adjunto) mensaje.attach(adjunto_MIME) sesion_smtp = smtplib.SMTP(email_smtp, '587') sesion_smtp.set_debuglevel(1) sesion_smtp.ehlo() sesion_smtp.starttls() sesion_smtp.login(sender_email_address, email_password) texto = mensaje.as_string() sesion_smtp.sendmail(remitente, destinatarios, texto) sesion_smtp.quit() -
Django debug toolbar loads but doesn't show on the local server even after proper installation
I have installed django debug toolbar correctly on a pipenv environment and done the main steps, such as adding internal_ips of 127.0.0.1 and adding the debug toolbar to installed_apps and middleware but still whenever I run the server and open a template of an app the debug toolbar doesn't show. However if I open the page source in the browser, it shows all the elements of the toolbar however the toolbar doesn't display, does anyone know what is going wrong and how I could fix it. -
Filtering data from 3 different tables in django with 1 intermediate table
I have four models in my django application with following structure: class User(models.Model): first_name = models.CharField() last_name = models.CharField() class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class SomeItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class SomeOtherItem(models.Model): some_item = models.ForeignKey(SomeItem, on_delete=models.CASCADE, unique=True) I have to create an API and I have been given a list of SomeItem. I have to write a django queryset line to filter first_name and last_name from User model, all details of SomeItem model and all details of SomeOtherItem model(if present). I also have to create a serializer to parse the data as a Python dict. Will be great if one can help me in this. -
"detail": "Authentication credentials were not provided." in django rest framework
I am trying to do an app on flutter with django rest framework backend. I want to log in as an already registered user and then I want to see only my active tasks, because further I want to end them after some time. The problem is I get "detail": "Authentication credentials were not provided." when I have made some changes in my code. I do the authentification with username and password. views.py class LoginAPI(APIView): def post(self, request): username = request.data['username'] password = request.data['password'] user = User.objects.filter(username=username).first() Token.objects.create(user=user) if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') payload = { 'id': user.id, #'username': user.username, #'password': user.password } token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8') response = Response() response.set_cookie(key='token', value=token, httponly=True) response.data = { 'token': token } print(user.id) return response class seeActiveTasks(ListAPIView): queryset = Tasks.objects.filter(is_active = 1) serializer_class = taskSerializer permission_classes = [IsAuthenticated] def get_queryset(self): print(self.request.user) print(self.request.user.id) # added string #return super().get_queryset().filter(user=self.request.user.id) return super().get_queryset().filter(user_id = self.request.user.id) login_page.dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; import 'package:phoneapp/main.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:phoneapp/screens/get_tasks.dart'; class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { bool _isLoading = false; @override Widget build(BuildContext context) { … -
Pytest does not raise ValidationError
I'm trying to test that a user can't be both agent and organizer but pytest doesn't raise ValidationError. models.py class User(AbstractUser): email = models.EmailField(unique=True) is_organizer = models.BooleanField(default=False) is_agent = models.BooleanField(default=False, ) def clean(self): super().clean() if self.is_organizer and self.is_agent: raise ValidationError("User can't be Agent and Organizer at the same time") test @pytest.mark.django_db() def test_user_cant_be_organizer_and_agent_at_the_same_time(): # user = User(username='ali', email='ali@gmail.com', password='a.123456', is_agent=False, is_organizer=True) # user.full_clean() with pytest.raises(ValidationError): User(username='a', email='a@gmail.com', password='a.123456', is_agent=True, is_organizer=True) pytest error core\tests\test_users.py:21 (test_user_cant_be_organizer_and_agent_at_the_same_time) @pytest.mark.django_db() def test_user_cant_be_organizer_and_agent_at_the_same_time(): # user = User(username='ali', email='ali@gmail.com', password='a.123456', is_agent=False, is_organizer=True) # user.full_clean() with pytest.raises(ValidationError): > User(username='a', email='a@gmail.com', password='a.123456', is_agent=True, is_organizer=True) E Failed: DID NOT RAISE <class 'django.core.exceptions.ValidationError'> test_users.py:28: Failed Destroying test database for alias 'default' ('test_crm')... -
google declined when i try to send email confirmation in django
This is the error when I try to send an email confirmation, any help rather than enabling a less secured app thank you (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials kw21-20020a170907771500b00731219a2797sm3559534ejc.210 - SMTP) -
How can I make django require a data migration when a condition changes?
I have a table containing a list of subclasses of a certain class in my django app. How can I make django require a data migration when this table is edited ? Is there some exception I can raise if django is started and one of these classes isn't in the table ? I'd also like to be able to hook into makemigrations so I can generate the correct data migration if possible. -
Docker doesn't see the table in the database after django migration
A Django project can be run in two ways: python manage.py runserver and using docker compose docker-compose up --build If run it the standard way (without docker), it works. If run it with docker, get an error that the database doesn't have the table relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... There are two containers gpanel_gpanel_1 and gpanel_db_1 I have tried migrations in 3 ways python manage.py migrate and docker-compose exec gpanel_db_1 python manage.py migrate and docker-compose exec gpanel_gpanel_1 python manage.py migrate And the last two methods did not display any information about the migration application in the console I also deleted the volumes gpanel_db_1 gpanel_gpanel_1 and re-created the container. But the error is still there. docker-compose.yaml version: "3.9" services: gpanel: restart: always build: . ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/gpanel depends_on: - db environment: - DB_HOST=db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} volumes: postgres_data: -
Python based HMI (communication between python-script and webapp)
I build a machine for quality-checking of assembled parts by capturing images and running a SVM on them. It's written in Python. Right now it's used via command line and displaying the captured images and inference-results in an OpenCV-Window. The main.py also handles other stuff like camera-communication and stepper-motor-control. Now I want to move the prototype to production so it has to be more user friendly. This means I need a webapp as Human-Machine-Interface. For now it just needs a button for the user to start the quality-check (trigger a function) and to display the momentary state ("moving", "idle", "error", "checking" etc.) as well as the resulting image. My initial approach is to just keep the main.py idle-ing until the start-button is pressed. But what would be the best way to interact between the webapp and the main.py? Would Websockets make sense? (I have never used them, just read about it) Or RESTAPI? I originally am a mechanical engineer, just self-taught the necessary python-skills for the task, so it's a little hard for me to properly describe the problem ;) Thanks! -
Django: Couldn't import Django, But django is installed (checked with django-admin --version, returns 4.1)
So i tried this: py manage.py runserver And got this error: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The virtual environmeent is activated (I have a little (venv) next to the path). Thing is, I just reinstalled django-admin via the virtual environment. Not only that but I did django-admin --version And got the result 4.1 Clearly it is installed. I can import django in IDLE just fine, but it won't run manage.py for some godforsaken reason. Any idea on how to fix this? -
How to get MIME type of FileField in DRF and send to parameters?
i hope everyone is good. I want to send mime type of the FileField in drf. but i dont know how to... { "id": 1, "document": "http://127.0.0.1:8000/images/articles_auth_with_user_eZUJmTW.png", "filesize": "239.55 KB", "filename": "articles_auth_with_user_eZUJmTW.png" "mimetype": "" }, This is response i am sending. I want to send mime type here... class DocumentModel(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID") document=models.FileField() class Meta: verbose_name_plural="Documents" ordering=["document"] def __str__(self): return f'{self.document}' @property def filesize(self): x = self.document.size y = 512000 if x < y: value = round(x / 1024, 2) ext = ' KB' elif x < y * 1024: value = round(x / (1024 * 1024), 2) ext = ' MB' else: value = round(x / (1024 * 1024 * 1024), 2) ext = ' GB' return str(value) + ext @property def filename(self): return self.document.name Above is my models file class DocumentSerializer(serializers.ModelSerializer): class Meta: model=DocumentModel fields = ['id', 'document', 'filesize', 'filename'] This is serializer code. Please kindly help ... -
How to let WebSocket in React through Content Security Policy on a deployed server
I am currently using Websockets in React to connect to Django channels. It works locally, but on a deployed server I get the following error, "Refused to connect to 'WEBSOCKET_URL' because it violates the following Content Security Policy directive: "default-src https: data: 'unsafe-inline' 'unsafe-eval'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback." I have tried the meta tag 'meta http-equiv="Content-Security-Policy" content="content-src 'self' ws://URL" /' but my login starts violating the Content Security Policy. Is there a way to add the websocket to the CSP without it interfering with other functions? -
Django/Flask : Rewritting an Flask Azure B2C authentication in Django
I want to use and Azure B2C authentication in Django, however there is no tutorial in Django for it but in Flask. However I never coded in Flask. I used the documentation/tutorial of microsoft that share a github with the flask code to do it : https://docs.microsoft.com/en-us/azure/active-directory-b2c/configure-authentication-sample-python-web-app?tabs=windows https://github.com/Azure-Samples/ms-identity-python-webapp I try to convert it in Django however I have an error that I do not understand ! The error message : Internal Server Error: /login/ TypeError: Object of type HttpResponseRedirect is not JSON serializable Here is the code views.py def index(request) : if not request.session.get("user"): return redirect("login") return render('index.html', user=request.session["user"] ) def login(request): # Technically we could use empty list [] as scopes to do just sign in, # here we choose to also collect end user consent upfront request.session["flow"] = _build_auth_code_flow(scopes=list(json.loads(os.getenv("SCOPE")))) return render(request, "login.html", {'auth_url' : request.session["flow"]["auth_uri"]}) def authorized(request): try: cache = _load_cache(request=request) result = _build_msal_app(cache=cache).acquire_token_by_auth_code_flow( request.session.get("flow", {}), request.args) if "error" in result: return render("auth_error.html", result=result) request.session["user"] = result.get("id_token_claims") _save_cache(cache=cache, request=request) except ValueError: # Usually caused by CSRF pass # Simply ignore them return redirect("index") def _load_cache(request): cache = msal.SerializableTokenCache() if request.session.get("token_cache"): cache.deserialize(request.ession["token_cache"]) return cache def _save_cache(cache, request): if cache.has_state_changed: request.session["token_cache"] = cache.serialize() def _build_msal_app(cache=None, authority=None): return msal.ConfidentialClientApplication( os.getenv("CLIENT_ID"), authority=authority …