Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CBV form_valid() and form_invalid() methods not called, form not saved to database
I tried following this tutorial: Link Whenever I try creating/updating/deleting a Record (my model, in this case) it redirects me to the page I've told it to redirect me to, and displays that a POST has been called in the command prompt, yet the Record is not created. I've tried overwriting both the form_valid() and form_invalid() functions, and added some print statements. Neither print statements print, so I don't believe either of these methods are called. Why are neither of these methods called, and why isn't my model being created and stored? Here's the model creation form, record_form.html: {% extends "catalog/base.html" %} {% block content %} <h1 class="text py-3 pt-4">Create/Update a Record!</h1> <style> .text { font-size: 40px; font-weight: bold; color: #060007; } </style> <div class="shadow p-3 mb-3 bg-light rounded"> <form class="form" method="POST" action="/catalog/"> {% csrf_token %} <p><label for="my_catalog">Catalog name:</label> {{ form.my_catalog }}</p> <p><label for="name">Name:</label> {{ form.name }}</p> <p><label for="description">Description:</label></p> <p>{{ form.description }}</p> <p><label for="date_start">Date start:</label> {{ form.date_start }}</p> <p><label for="date_end">Date end:</label> {{ form.date_end }}</p> <p><label for="manufacturer">Manufacturer:</label> {{ form.manufacturer }}</p> <p><label for="condition_rating">Condition rating (between 0 and 5):</label> {{ form.condition_rating }}</p> <p><label for="condition_description">Condition description:</label></p> <p>{{ form.condition_description }}</p> <div><input type="submit" value="Save"></div> </form> <style> .form { color: #060007; } </style> </div> {% endblock content … -
Docker - Django - PermissionError after switching to Host volumes on Ubuntu Server
The Docker image / container worked fine on Ubuntu, however I wanted to have access to the static folder. Therefore I added "Host volumes" to the docker-compose.yml (volumes was empty before): version: '3.3' services: api: build: context: . restart: always ports: - "8000:8000" volumes: - ./app_static:/app/static $ docker-compose up After building the image and running the python manage.py collectstatic command, I get the following error: PermissionError: [Errno 13] Permission denied: 'static/media' The folder structure inside the docker image looks like this: appuser@1e2bc02404a2:/app$ ls -la total 24 drwxr-xr-x 1 appuser appuser 4096 Mar 29 21:50 . drwxr-xr-x 1 root root 4096 Mar 29 21:51 .. drwxr-xr-x 1 appuser appuser 4096 Mar 29 21:00 api -rw-r--r-- 1 appuser appuser 765 Mar 29 21:00 manage.py drwxr-xr-x 1 appuser appuser 4096 Mar 29 21:00 mausefallentest drwxr-xr-x 2 root root 4096 Mar 29 21:51 static The problem is, that after adding Host volumes to the docker-compose file, the user for the static folder changed to root. But the Docker image is runnung under the "appuser" user. Thus i get the permission denied error. But how can i solve this problem ? I only have this problem on my Ubuntu server. On Windows its working fine. -
Unable to Save images to database
am unable to save images containing url on database this will give me an error if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' this error is as a result of my attempts to save this scrapped image with beautiful soup below are images list that refused to be saved on my models , this images are been scrapped with beautiful soup something like this brought the images images = [i['data-src'] for i in soup.find_all('img', {'class','attachment-jnews-750x375 size-jnews-750x375 lazyload wp-post-image'})] https://people.net/wp-content/uploads/2021/03/ad1-746x375.jpg https://people.net/wp-content/uploads/2020/08/caroon-1-600x375.jpg why this code brought the above error Post.objects.create( title=title, content_1=paragraphs, image=images, sources=lnk, ) this is my model.py example code class Post(models.Model): title = models.CharField(max_length=250, blank = True, help_text='Maximum 160 Title characters.') image = models.FileField(upload_to='images', blank=True, null=True, help_text='You must upload original image before continuing.') but i get this error if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' but if am saving normal jpeg file it is always a success. how do i save this scrapped images to models -
django braintree authorization error generating token
im trying to integrate django with braintree but im getting authorization error everything seems fine but when i place order after filling the order form i get error: AuthorizationError at /payment/process/ line 39, in payment_process caused by this line :client_token = gateway.client_token.generate() my views.py import braintree from django.shortcuts import render, redirect, get_object_or_404 from django.conf import settings from order.models import Order # instantiate Braintree payment gateway gateway = braintree.BraintreeGateway(settings.BRAINTREE_CONF) def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) total_cost = order.get_total_cost() if request.method == 'POST': # retrieve nonce nonce = request.POST.get('payment_method_nonce', None) # create and submit transaction result = gateway.transaction.sale({ 'amount': f'{total_cost:.2f}', 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # mark the order as paid order.paid = True # store the unique transaction id order.braintree_id = result.transaction.id order.save() return redirect('payment:done') else: return redirect('payment:canceled') else: # generate token client_token = gateway.client_token.generate() return render(request, 'payment/process.html', {'order': order, 'client_token': client_token}) def payment_done(request): return render(request, 'payment/done.html') def payment_canceled(request): return render(request, 'payment/canceled.html') my process template {% extends "shop/base.html" %} {% block title %}Pay by credit card{% endblock %} {% block content %} <h1>Pay by credit card</h1> <form id="payment" method="post"> <label for="card-number">Card Number</label> <div id="card-number" class="field"></div> <label for="cvv">CVV</label> <div id="cvv" class="field"></div> <label for="expiration-date">Expiration Date</label> … -
Django Python iterate attribute of object from list
i have a set of atributes stored on list, and i have an object called customuser, i want to iterate its attribute from the list and display value from database fieldx={'department','usertype','company'} for f in fieldx: print(customuser.f) but i get the following error message: 'CustomUser' object has no attribute 'f' can you help me with this many thanks -
how can insert multiple record using
I'm working on a small project Django Rest Framework, I already create add contact function as you can see in my create function. now I'm working on bulk import, but when I submit my data as a list not as a dict I get an error message : {"non_field_errors":["Invalid data. Expected a dictionary, but got list."]} this is my code to add a contact, class ContactView(ListModelMixin, viewsets.GenericViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer def create(self, request): serializeObject = ContactSerializer(data = request.data) if serializeObject.is_valid(): serializeObject.save() contactObject = Contact.objects.all() contactSerializer = ContactSerializer(contactObject, many=True) return Response(contactSerializer.data, status = status.HTTP_201_CREATED) return Response(serializeObject.errors, status.HTTP_400_BAD_REQUEST) Now i would like to create another function, for bulk create, since i have a list -
Error: Unknown option '--output' React & Django
In my package.json file I have: "scripts": { "dev": "webpack --mode development ./x/frontend/src/index.js --output ./x/frontend/static/frontend/main.js", "build": "webpack --mode production ./x/frontend/src/index.js --output ./x/frontend/static/frontend/main.js" }, and when I try to run this command: npm run build it shows me an error: [webpack-cli] Error: Unknown option '--output' How can I fix this? -
Should i use proxy models in django?
im here trying to start a new project, in django and i came across this problem, while creating the models My users will be different types of users, so i was thinking, should i use proxy models for it? because here is how it´s going to be the realtionship between them. i will have a client, and a personal trainer, and the admin of course, but the problem here is that the client is going to have a ForeignKey with personal trainer, my main question is, can i create in a proxy model an extra field where i establish the relationship with personal trainer proxy model? If not, is there any other way that i can aproach this type of situation Thanks in advance -
Dockerize Django with Celery worker/beat, RabbitMQ and postgresql
I want to setup docker-compose for my app, which contains Django, Celery (+Beat), RabbitMQ and PSQL. My problem is that celery beat container does not work as intended (does not schedule a task with interval 10s). Docker logs - celery beat wakes up in 5.00 minutes, celery worker works fine celery-worker_1 | [2021-03-29 21:05:58,201: INFO/MainProcess] mingle: all alone celery-worker_1 | [2021-03-29 21:05:58,225: WARNING/MainProcess] /usr/local/lib/python3.9/site-packages/celery/fixups/django.py:205: UserWarning: Using settings.DEBUG leads to a memory celery-worker_1 | leak, never use this setting in production environments! celery-worker_1 | warnings.warn('''Using settings.DEBUG leads to a memory celery-worker_1 | [2021-03-29 21:05:58,225: INFO/MainProcess] celery@247ea26ee17b ready. celery-beat_1 | [2021-03-29 21:06:00,525: DEBUG/MainProcess] Setting default socket timeout to 30 celery-beat_1 | [2021-03-29 21:06:00,526: INFO/MainProcess] beat: Starting... celery-beat_1 | [2021-03-29 21:06:00,749: DEBUG/MainProcess] Current schedule: celery-beat_1 | <ScheduleEntry: celery.backend_cleanup celery.backend_cleanup() <crontab: 0 4 * * * (m/h/d/dM/MY)> celery-beat_1 | [2021-03-29 21:06:00,749: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes celery-beat_1 | [2021-03-29 21:06:00,751: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. Dockerfile FROM python:3 ENV PYTHONBUFFERED=1 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt docker-compose.yml version: '3.8' services: server: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" env_file: - .env depends_on: - pgdb - rabbit - celery-worker celery-worker: build: … -
django oauth toolkit `or` in required scopes in view
I'm using drf and oauth toolkit with IsAuthenticatedOrTokenHasScope permissions as default. I have a view that contains scopes required_scopes = ['mod', 'admin'] When users logs into the app he have special groups which define his permission scope. So when the moderator logs into the app he gets mod scope. When he calls my view he gets 403 because allow_scopes in AccessToken model returns False. That is because the resource_scopes is ['mod', 'admin'] and provided_scopes is 'mod'. When method allow_scopes checks resource_scopes.issubset(provided_scopes) she returns False which is not intentional in my case. Is there any other option without overwriting allow_scopes in AccessToken model to define that this view needs scope mod or scope admin. ? -
How to objects.get/objects.filter from a "through" class?
im a beginner at django - so im a bit lost with how to go about this. I have three classes: Recipe, Ingredient and IngredientAmount - where IngredientAmount acts a "through" class class IngredientAmount(models.Model): SINGLE = 1 DOUBLE = 2 TRIPLE = 3 AMOUNT_CHOICES = ( (SINGLE, 'Single'), (DOUBLE, 'Double'), (TRIPLE, 'Triple'), ) recipe = models.ForeignKey( 'Recipe', related_name='ingredient_amounts', on_delete=models.SET_NULL, null=True) ingredient = models.ForeignKey( 'Ingredient', related_name='ingredient_amounts', on_delete=models.SET_NULL, null=True, blank=True) amount = models.IntegerField(choices=AMOUNT_CHOICES, default=SINGLE) def __str__(self): return f'Recipe = {self.recipe}, Ingredient = {self.ingredient}, Amount = {self.amount}' they connect to my Recipe class class Recipe(models.Model): alphanumeric = RegexValidator( r'[a-zA-Z][a-zA-Z ]+', 'Only alphabet characters and spaces are allowed.') title = models.CharField(max_length=30, null=True, validators=[alphanumeric]) description = models.TextField(max_length=200, null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) slug = models.SlugField(null=False, unique=True) ingredients = models.ManyToManyField( 'Ingredient', through='IngredientAmount', related_name='recipes') def __str__(self): return self.title def get_absolute_url(self): return reverse('recipe:recipe_detail', kwargs={'slug': self.slug}) the Ingredient class is a simple one with just 'name' variable: class Ingredient(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name And i managed to use a slug to get a RecipeDetail page in my views.py: def recipeDetail(request, slug): recipe = get_object_or_404(Recipe, slug=slug) return render(request, 'recipe/recipe_detail.html', {'recipe': recipe}) So in my templates I can now display the data … -
Why is Python .title() sticky? Applying title case to future strings?
This is a strange one: I'm trying to format a string in python (obviously), and when I use string.title(), it seems like python keeps applying title case to the string, even after applying other formatting to the string. Here's my code: def format_trade_name(self): tr_name = self.trade_name.title() tr_cap = [ 'oxy', 'depo', 'edex', 'emla', 'pred', ] tr_join = '|'.join(tr_cap) tr_regex = r'\b(?!(' +tr_join + r'))(\w{1,4})\b' print(tr_regex) tr_matches = re.search(tr_regex, self.trade_name,re.IGNORECASE) print(tr_matches.groups()) for i in tr_matches.groups(): if i is not None: tr_name = re.sub(r'\b'+i+r'\b',i.upper(),tr_name) print(tr_name) return tr_name Here's the problem: I want the function to capitalize the first letter of each word, and then convert all 4 letter strings (not in tr_cap) to upper case. So if the original string is tylenol depo er, I want the formatted string to be Tylenol Depo ER When I change the 2nd line to tr_name = self.trade_name.capitalize(), my function changes tylenol depo er into Tylenol depo ER (depo is not capitalized). When I keep the 2nd line as as written, tr_name = self.trade_name.title(), my function changes tylenol depo er to Tylenol Depo Er (Er isn't upper case, even though the formatting was applied after using .title(). Can anyone explain to me why the string is … -
Are django signals the correct tool to do post-upload processing?
I'm building a website where I want the website admin to be able to upload a pdf file via the admin site and then for those files to be downloadable via clickable images somewhere on the site (the images would be generated based on the first page of the pdf). I was thinking, I'd use django signals to generate these images every time a pdf is uploaded like so: class Forms(models.Model): name = models.CharField(max_length=200) upload = models.FileField(upload_to='main/data/forms/', validators=[FileExtensionValidator(['pdf'])]) @receiver(post_save, sender=Forms) def generate_image(sender, **kwargs): //do some image generation here Are signals the right tool for this job? I've been reading tutorials about django signals, and it's emphasized that they should only be used for communication between different parts of the code, or for decoupling your code. Is there a better tool to accomplish what I want? P.S. This is my first ever stackoverflow question. I'm super excited, but if I made some faux pas while posting, please tell me! -
django admin how to add context when using custom action button?
I have a custom action button "Add post" for each record in my admin panel. I want to save in context obj.id to use it for a default value in admin:channels_post_add form class ChannelAdmin(admin.ModelAdmin): list_display = ['title','username', 'invite_link', 'account_actions'] def account_actions(self, obj): !!!! I WANT TO ADD CONTEXT HERE!!!! return format_html('<a class="button" href="{}">Add post</a>', reverse('admin:channels_post_add')) account_actions.short_description = 'Actions' account_actions.allow_tags = True class Meta: model = Channel admin.site.register(Channel, ChannelAdmin) class PostAdmin(admin.ModelAdmin): list_display = ['text', 'media', 'send_type', 'created'] class Meta: model = Post def get_form(self, request, obj=None, **kwargs): form = super(PostAdmin, self).get_form(request, obj, **kwargs) try: post_id = !!! AND USE IT HERE!!!! form.base_fields['channels'].initial = post_id except Exception as e: print(e) return form -
AJAX part of the javascript function doesn't work on my Django Project
I am creating an app using firebase authentication. User id and user email values are stored in firabase because login methods like email/password login, facebook login, google login are included with firebase. But another values needed to store like gender, phone, birth date. Because of that I am trying to get user id and email values with ajax after that I can save in local database like SQLite in development environment. My problem is I can't pass user id value with ajax get request. Here are my codes. I initialized the firebase already. At the below code function is running properly.And else block is running properly too. But AJAX section doesn't working no success no failure no ajax is working. <script> function checkUser() { firebase.auth().onAuthStateChanged(function(user) { if (!user) { window.location.replace("{% url 'app:index' %}"); } else { alert('User is active'); document.getElementById("uid").value = user.uid; document.getElementById("email").value = user.email; $.ajax({ type: "GET", url: "{% url 'app:edit_profile' %}", data: { "email": user.email, "uid": user.uid, }, success: function(data){ console.log("success"); console.log(data); }, failure: function(data){ console.log("failure"); console.log(data); }, }); } }); } window.onload = function() { checkUser(); }; My Django view is this: def edit_profile(request): if request.method == 'POST': return edit_profile_post(request) else: uid = request.GET.get("uid", None) print('UID -----> … -
For loop in django html depending on the index (repeat every 3 times)
I am working with a bootstrap template for a django app <div class="row"> <div class="col-12"> <div class="card-deck-wrapper"> <div class="card-deck"> {% if posts %} {% for post in posts %} <div class="card d-block"> <img class="card-img-top" src="{{ post.image }}" height="200"> <div class="card-body"> <h5 class="card-title">{{ post.title }}</h5> <p class="card-text">{{ post.description }}</p> <p class="card-text"> <small class="text-muted">{{ post.creation_date }}</small> </p> </div> </div> <!-- end card--> {% endfor %} {% endif %} </div> <!-- end card-deck--> </div> <!-- end card-deck-wrapper--> </div> <!-- end col--> </div><!-- end row --> Mi main target is to repeat each "card" just 3 times, otherwise the templates looks awful, but have no idea how to iterate just 3 times, and at the 4th, 7th, 10th, and so on time, create a new "card-deck" to continue with post 4-5-6, then another "card-deck" for post 7-8-9 and so on Thank you! -
Django, The 'image' attribute has no file associated with it
I'm getting this strange error The 'image' attribute has no file associated with it. when I'm trying to register new user. I have a signal that creates profile for new user and when this error happens, user gets registered but profile is not created. Here is my code: #views.py def registration(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = RegistrationForm() return render(request, 'registration.html', {'form': form}) #models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path_ppic, null=True, blank=True) #signals.py: @receiver(post_save, sender=User) def create_profile(sender, instance, **kwargs): Profile.objects.create(user=instance) -
Probem to install psycopg2
I'm trying to install psycopg2 with pip3 install psycopg2 and getting this error It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and try again. after this I runned pip3 install psycopg2-binary but still getting this error I tried to run sudo apt install python3-dev libpq-dev and returned: Reading package lists... Done Building dependency tree Reading state information... Done python3-dev is already the newest version (3.8.2-0ubuntu2). Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: libpq-dev : Depends: libpq5 (= 12.6-0ubuntu0.20.04.1) but 13.2-1.pgdg20.04+1 is to be installed E: Unable to correct problems, you have held broken packages. I'm improving my English, be patient. -
How to use Google Maps with Django
I'm completely new to Django and maps, can someone help me with a guide or a project to refer and start. Want to implement Google maps with django to display a dynamic map on my homepage, I referred to the docs but can't figure out how to implement it -
How to add fields to the django user model
I am trying to add an 'address' field to the my user 'Profile' model, but only the email, first name and last name fields are appearing. forms.py: class RegisterForm(UserCreationForm): email = forms.EmailField() address = forms.CharField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'address', 'email', 'password1', 'password2'] models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username}' I have added the email field and it appears on the list, however, the address field doesn't appear -
How to abstract dash plotly component into another file with a callback?
Currently, I have my application python file separated with the specific component in the Django framework. I have seen a lot of examples writing each component with callback in the same file with the app python file. I am wondering how to write the update_output_div() function in a file with callback and let the app call it? Thank you so much! app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.layout = html.Div([ ... ]) @app.callback( Output(component_id='my-output', component_property='children'), Input(component_id='my-input', component_property='value') ) def update_output_div(input_value): return 'Output: {}'.format(input_value) if __name__ == '__main__': app.run_server(debug=True) -
Django logger settings
I am trying to create a log file for each APIs. I get the response from the API. But it not generate log files. In my logger_settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'large': { 'format': '%(username)s %(asctime)s %(levelname)s %(process)d %(pathname)s %(funcName)s %(lineno)d %(message)s' }, 'tiny': { 'format': '%(asctime)s %(message)s ' } }, 'handlers': { 'errors_file': { 'level': 'ERROR', 'class': 'logging.handlers.TimedRotatingFileHandler', 'when': 'midnight', 'interval': 1, 'filename': './logs/error.log', 'formatter': 'large', }, 'info_file': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'when': 'midnight', 'interval': 1, 'filename': './logs/info.log', 'formatter': 'large', }, }, 'loggers': { 'error_logger': { 'handlers': ['errors_file'], 'level': 'WARNING', 'propagate': False, }, 'info_logger': { 'handlers': ['info_file'], 'level': 'INFO', 'propagate': False, }, }, } In my views.py: def list(self, request, *args, **kwargs): try: logging.getLogger("info_logger").info(repr('try period list'), extra={ 'Start period list api requested by': self.request.user}) .... response['status_code'] = 200 logging.getLogger("info_logger").info(repr("End period list api inside else"), extra={ 'requested by': self.request.user}) return Response(response, status=status.HTTP_200_OK) except Exception as e: logging.getLogger("error-log").error(repr('try period list'), extra={ 'error in period list api requested by': self.request.user}) massage = str(e) response = get_error_details(massage) return Response(response) when I am hitting list API it create info.log file. But inside file(info.log) it showing nothing... :( I miss anything??? -
Django - Customize error email sent to admins using mail_admins in logging. Too much sensetive information
The current email that goes out to admins during errors contains sensitive information so I'd like to change course and instead include instructions on how to quickly view the log files and find the traceback. I'm not sure how to piggyback off the current functionality and add a custom message rather than the standard message. So any help would be awesome. -
Django/DRF endpoint to serve SVG static files
I'm building an API with Django and Django Rest Framework. I'm stuck in building an endpoint to serve a collection of SVG files (some fun emojis :P). These SVG files aren't stored in the DB (hence I don't have a Django Model for them), instead they are in the project's static folder where dey have their own sub-folder: | project | + static | | + assets | | | + emojis | | | | | smile.svg | | | | | laugh.svg | | | | | etc... I have tried different approaches but I'm not sure. One was the following view: # Python from os import listdir from os.path import isfile, join # Django from django.http import HttpResponse def list_emojis(request): emojis_path = 'project/static/assets/emojis/' emojis = [f for f in listdir(emojis_path) if isfile(join(emojis_path, f))] ret = [] for emoji in emojis: ret.append(open(emojis_path+emoji, 'r')) return HttpResponse(ret, content_type='multipart/form-data') This is returning a binary file downloaded (when I go to the URL with my browser) which looks like this: <_io.TextIOWrapper name='project/static/assets/emojis/094-user.svg' mode='r' encoding='UTF-8'><_io.TextIOWrapper name='project/static/assets/emojis/059-sad-11.svg' mode='r' encoding='UTF-8'><_io.TextIOWrapper name='project/static/assets/emojis/006-shooting-star.svg' mode='r' encoding='UTF-8'><_io.TextIOWrapper name='project/static/assets/emojis/120-briefcase.svg' mode='r' encoding='UTF-8'><_io.TextIOWrapper name='project/static/assets/emojis/016-monkey.svg' mode='r' encoding='UTF-8'><_io.TextIOWrapper name='project/static/assets/emojis/185-tongue.svg' mode='r' encoding='UTF-8'> I have never returned files from an API before. What would be the … -
Can DRF Simple JWT be used to validate a token it didn't generate?
I'm using @azure/msal-react for AAD authentication on the client. It returns an accessToken and an idToken that I need to send to my Django/DRF API where they need to be validated, user it belongs to found or created if they don't exist, and then a JWT issued back to allow further client-API communication. I'm currently sending the accessToken in the header as Authorization: Bearer <accessToken>. Because I have the following in my settings.py, I am getting Unauthorized: /api/v2/auth/aad_token/validate/: 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), The response says: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } It looks like it the DEFAULT_AUTHENTICATION_CLASSES is intercepting it and can't validate it, I assume because it is one it didn't generate. Due to this, I was about to start writing DRF custom authentication that subclasses BaseAuthentication, permitting the HTTP_AUTHORIZATION to be received where I can do with it what I need. However, I read the Microsoft documentation a few more times, these parts in particular: There are also several third-party open-source libraries available for JWT validation - there is at least one option for almost every …