Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the correct way to configure ASGI application for channels in Django?
I've just started to learn about channels and asgi in django in few tutorials that i've seen they do this to configure the asgi apllication asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') application = ProtocolTypeRouter({ 'http':get_asgi_application(), }) settings.py INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat' ] ASGI_APPLICATION = 'config.asgi.application' to check when i run my server it was supposed to be running on asgi/channel server like this Starting ASGI/Channels version development server at http://127.0.0.1:8000/ but mine is still running on the default one Starting development server at http://127.0.0.1:8000/ when i use daphne and put inside installed apps instead of channels 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat' ] it works fine Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ can someone tell me what is going on here?and how exactly django works with asgi? -
Not entering Else Statement from user.is_authenticated
In the castmascotvote view, everything is working when I'm authenticated, but not working otherwise. I have a print('entering not authenticated') right when it enters the else statement if the user isn't authenticated, but it never enters it, i'm boggled. I don't understand at all why it's not working. does anyone have any idea where I should start looking? error message The view didn't return an HttpResponse object. It returned None instead. But I clearly have a HttpResponse object! .html <form class="mascotvoteform" action="{% url 'castmascotvote' mascot.id %}" id="{{mascot.id}}"> <div class="p-0"><h4>{{ mascot.name }} </h4> <p> by {{ mascot.author }} </p></div> <div class="p-0"><img class="img-thumbnail" src="{{ mascot.image.url }}" style="width:250px;"></div> <div class="row p-3"> {% if mascot.total_votes is 0 %} <div class="col"><h5 id="mascotvotes{{mascot.id}}">0</h5></div> <button class="col btn btn-primary" type="submit" id="castmascotvote{{mascot.id}}">Vote</button> {% else %} <div class="p-0 col"><h5 id="mascotvotes{{mascot.id}}">{{ mascot.total_votes }}</h5></div> <button class="col btn btn-primary" type="submit" id="castmascotvote{{mascot.id}}">Vote</button> {% endif %} </div> </form> .script $( document ).ready(function() { $(".mascotvoteform").submit(function(e) { {% if user.is_authenticated %} e.preventDefault() {% endif %} let mascot_id = $(this).attr("id"); let url = $(this).attr('action'); $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'mascot_id': mascot_id, }, success: function(response) { console.log('success', response) $(`#mascotvotes${mascot_id}`).text(`${response['total_votes']}`) }; }, error: function(response) { console.log('error', response) } }); }) .views def castmascotvote(request, mascot_id): mascot = … -
How to handle variable replacement in dev vs rollup build?
I am making a site that was based off Open Web Components Generator. I hit the same issue of process not being defined for redux as this SO question: lit-element with rollup and redux: process is not defined I am confused because the top answer says to use Rollup's replace plugin. This works great for the built version from the generator's package.json which runs the following: "build": "rimraf dist && tsc && rollup -c rollup.config.js && npm run analyze -- --exclude dist", However when I'm just doing dev watcher the command is this: "start": "tsc && concurrently -k -r \"tsc --watch --preserveWatchOutput\" \"wds\"" Rollup isn't going to run while just doing a dev watcher like this so I'm not sure how to solve the problem when doing dev as opposed to building. Meanwhile the Redux maintainer on the original post, says to use an artifact when not bundling with something via Rollup. My code is like the following so I'm not sure how to satisfy both conditions. import { configureStore, EnhancedStore, } from '@reduxjs/toolkit'; I wonder if this is an issue on me, or Open WC not using Rollup watch under the hood? -
problem with SQLite when deploying Django Website on AWS, cant properly instal pysqlite
`I have made Django blog. I encountered this error after deploy when trying to visit my website on AWS: Django - deterministic=True requires SQLite 3.8.3 or higher upon running python manage.py runserver So I found this solution: Django - deterministic=True requires SQLite 3.8.3 or higher upon running python manage.py runserver So i understand it like this: In ubuntu terminal i type : sudo apt install python3.10-venv to install envirement Then in my Django project in Visual Studio i type python3 -m venv django_my_site to create virtual env Now i click "+" to open this env and type pip3 install pysqlite3 and pip3 install pysqlite3-binary After that i type python3 -m pip freeze > requirements.txt and i get requirements.txt file which looks like that: asgiref==3.6.0 Django==4.1.4 Pillow==9.3.0 pysqlite3==0.5.0 pysqlite3-binary==0.5.0 sqlparse==0.4.3 Now AWS have problem with installing pysqlite3. How to properly install pysqlite3 on AWS? Encountered error while trying to install package. pysqlite3` note: This is an issue with the package mentioned above, not pip. hint: See above for output from the failure. src/blob.h:4:10: fatal error: sqlite3.h: No such file or directory #include "sqlite3.h" ^~~~~~~~~~~ compilation terminated. LINK TO MY REPOSITORY: https://github.com/Stanotech/my_site.git I tried to deploy site with sqlite with no success, … -
How to create a crypto payment invoice generator app?
I want to create an application that generates invoices in order to receive crypyo payment but I don't know where to start. I code in django and react and I request any idea, tool, framework, github similar project or anything that can help me develop my project. -
Bootstrap 4 close button not working django
enter image description hereI have a close button on my alert but when I click on it it doesn't close. I have seen similar people with the same problem but none of the solutions have worked for me This is what I currently have {% for message in messages %} <div class="container-fluid p-0"> <div class="alert {{ message.tags }} alert-dismissible fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {{ message }} </div> </div> {% endfor %} -
Query only specific subclass(es) of an abstract superclass
This question is fundamentally similar to these previous questions: Django access to subclasses items from abstract class How to query abstract-class-based objects in Django? I am posting this as a new, separate question because: I have minor additional considerations that aren't addressed in the previous questions The previous questions are relatively old, and if it's the case that the correct answer has changed in recent times, I wonder if maybe those questions haven't been visible enough (given that they have accepted answers) to get the attention of those who might know about such potential changes. With that in mind, I'll take the question from the top and define it fully and concretely - and I leave it to the hive to determine if a close-duplicate is in order. Background Say I am constructing models to represent parts of a building. I split the building into logical classes: Floor BuildingSpace(ABC) Office(BuildingSpace) CommonArea(BuildingSpace) Goal Under Floor, I want methods that can retrieve all buildingspaces - or, either of its two subclasses separately: from typing import Type class Floor(models.Model): def getAllSpaces(): # return all objects that satisfy Type[BuildingSpace] def getAllOffices(): # return all objects that satisfy strictly and only Type[Office] def getAllCommonAreas(): # … -
Django inline formset not valid on update
My create method works perfectly but the update does not, it returns 1 error for each inline as an empty list [] forms.py StructureFormset = inlineformset_factory(Plan, Structure, fields = ( 'material_type', 'weight', 'thickness', 'provider' ), extra=0, can_delete=True ) TestFormset = inlineformset_factory(Plan, Test, fields=( 'essay', 'critic', 'spec' ), extra = 0, can_delete=True ) class PlanForm(ModelForm): class Meta: model = Plan fields = ( 'format', 'pc', 'revission', 'rev_date', 'client', 'product', 'gp_code', 'code', 'observation', 'continuation', 'dispatch_conditions', 'elaborator', 'reviewer' ) localized_fields=('rev_date',) views.py def editPlan(request, pk): plan = Plan.objects.get(id = pk) form = PlanForm(instance = plan) sformset = StructureFormset(instance=plan) tformset = TestFormset(instance=plan) context = { 'form': form, 'sformset': sformset, 'tformset': tformset } if request.method == 'POST': print('----------------------------request----------------------------') print(request.POST) form = PlanForm(request.POST, instance = plan) sformset = StructureFormset(request.POST, instance=plan, prefix='structure') tformset = TestFormset(request.POST, instance=plan, prefix='test') if form.is_valid() and sformset.is_valid() and tformset.is_valid(): print('-----------------------is valid-----------------------') form.save() instances = sformset.save(commit=False) for instance in instances: sformset.save_m2m() instance.save() tformset.save() return redirect('/plans/') else:#printing errors print('-----------------------is not valid-----------------------') print(sformset.total_error_count()) print(sformset.errors) print(tformset.total_error_count()) print(tformset.errors) return render(request, 'home/plan_forms.html', context) template.html {{ tformset.management_form }} <table> <thead> <tr> <th>Essay</th> <th> <abb title="Critical Variable">Crit.</abb> </th> <th>Spec</th> {% if tformset.instance.pk %} <th class="text-center px-1 col-1 pb-2"> <i class="material-icons">delete</i> </th> {% endif %} </tr> </thead> <tbody id="tform_set"> <!--Test form goes here--> … -
Bad Request (400) in django web app in Azure App service while adding Custom Domain
In the Azure app service my Website is working fine with something.azurewebsites.net with the following code ALLOWED_HOSTS = [os.environ['WEBSITE_HOSTNAME']] if 'WEBSITE_HOSTNAME' in os.environ else [] But while adding a custom domain, it is showing as Bad Request (400). I think the problem relies on the Allowed host, and the Django app is not allowing my custom domain. I couldn't find a solution or a perfect line of code to resolve this issue. -
Does MongoEngine have an "AutoField()" like Django?
I just switched from SQL to MongoDB. When I was changing all my model fields from Django fields to MongoEngine fields, I realized there was no AutoField(). Does anyone know a substitute for this? -
How Can I Check For The Existence of a UUID
I am trying to check for the existence of a UUID as a primary key in my Django environment...and when it exists...my code works fine...But if it's not present I get a "" is not a Valid UUID... Here's my code.... uuid_exists = Book.objects.filter(id=self.object.author_pk,is_active="True").first() I've tried other variations of this with .exists() or .all()...but I keep getting the ['“” is not a valid UUID.'] error. I did come up with a workaround.... if self.object.author_pk is not '': book_exists = Book.objects.filter(id=self.object.author_pk,is_active="True").first() context['author_exists'] = author_exists Is this the best way to do this? I was hoping to be able to use a straight filter...without clarifying logic....But I've worked all afternoon and can't seem to come up with anything better. Thanks in advance for any feedback or comments. -
Django Channels: Channel Name type error appears when loading web socket chat
I'm building a basic websocket live chat using Django Channels and while the site loads fine, when I enter into the site, in my terminal I get this TypeError Message: TypeError: Channel name must be a valid unicode string with length < 100 containing only ASCII alphanumerics, hyphens, underscores, or periods, not RedisChannelLayer(hosts=[{'host': '127.0.0.1', 'port': 6379}]) Im assuming the problem lies in my settings.py file but based on my current channel layer settings, I don't see what the problem is: CHANNEL_LAYERS = { 'default': { "BACKEND": 'channels_redis.core.RedisChannelLayer', "CONFIG": { "hosts": [('127.0.0.1', 6379)], }, }, } I'm new to django and channels so maybe theres a place where I defined the channel name and i'm just missing but I'm not sure or where to look for it if thats true. -
Signup and Login form post data withou specifying path
I just discovered a probable BUG in my code that allows user to signup or login action attribute is blank. Here is what i mean login.html <!DOCTYPE html> <html class="supernova"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>SignIn</title> <link rel="stylesheet" href="/static/signup/css/1.css"> <link rel="stylesheet" href="/static/signup/css/2.css"> <link rel="stylesheet" href="/static/signup/css/3.css"> <link rel="stylesheet" href="/static/signup/css/4.css"> <link rel="stylesheet" href="/static/signup/css/5.css"> <link rel="stylesheet" href="/static/signup/css/6.css"> <script src="/static/signup/js/1.js"></script> <script src="/static/signup/js/2.js"></script> <script src="/static/signup/js/3.js"></script> <script src="/static/signup/js/4.js"></script> <script src="/static/signup/js/5.js"></script> <script src="/static/signup/js/6.js"></script> </head> <body> <form class="jotform-form" action="" method="post" enctype="multipart/form-data" name="form_230023299150548" id="230023299150548" accept-charset="utf-8" autocomplete="on"> {% csrf_token %} <div role="main" class="form-all"> <ul class="form-section page-section"> <li id="cid_60" class="form-input-wide" data-type="control_head"> <div class="form-header-group header-small"> <div class="header-text httal htvam"> <h3 id="header_60" class="form-header" data-component="header">SignIn</h3> </div> </div> </li> <li class="form-line jf-required" data-type="control_textbox" id="id_64"> <label class="form-label form-label-left" id="label_64" for="input_64"> Username <span class="form-required">*</span> </label> <div id="cid_64" class="form-input jf-required"> {{form.username}} </div> </li> <li class="form-line jf-required" data-type="control_fullname" id="id_66"> <label class="form-label form-label-left form-label-auto" id="label_66" for="first_66">Password <span class="form-required">*</span> </label> <div id="cid_66" class="form-input jf-required"> <div data-wrapper-react="true"> <span class="form-sub-label-container" style="vertical-align:top" data-input-type="first"> {{form.password}} </span> </div> </li> <li class="form-line" data-type="control_button" id="id_76"> <div id="cid_76" class="form-input-wide"> <div data-align="center" class="form-buttons-wrapper form-buttons-center jsTest-button-wrapperField"><button id="input_76" type="submit" class="form-submit-button submit-button jf-form-buttons jsTest-submitField" data-component="button" data-content="">Submit</button></div> </div> </li> </ul> </div>/ <!-- <div class="formFooter-heightMask"></div> <div class="formFooter f6 branding21"></div> --> </form> </body> </html> In the opening form tag, i am yet to specify the path … -
Django CBV: How come my child method is not overriding my parent method?
I'm pretty new when it comes to python classes / django CBVs. I'm trying to have a method (print_test) from my child class override my parent class, but I can't get it to work. What am I doing wrong? Below is my parent: This is my child: I've tried a bunch of things but can't see to get it to work :/ Appreciate all help! -
Django - Save form fields while paging
This will be a lengthy post, please have patience with me, I just started with Django and try to wrap my head around it. I created a site that will go thru exam questions one at a time, displaying the question and the multiple choice answers like on countless other websites. The challenge I experience is when the user clicks "NEXT" on the pagination buttons, I would like for the selected answer(option) to be saved back to the database. I tried it with AJAX scripts but the view never got executed. Maybe there is a better way to do this or could you please point me into the right direction? I will post all of my code and hope someone can please assist me. Thank you for taking the time to look at this. I start with the models.py: from django.db import models class QuesModel(models.Model): question = models.TextField(null=True) code_snippet = models.TextField(null=True) op1 = models.CharField(max_length=200,null=True) op2 = models.CharField(max_length=200,null=True) op3 = models.CharField(max_length=200,null=True) op4 = models.CharField(max_length=200,null=True) ans = models.CharField(max_length=200,null=True) def __str__(self): return self.question class Answer(models.Model): ans_id = models.AutoField(primary_key=True) question_id = models.ForeignKey(QuesModel, on_delete=models.CASCADE) fname = models.CharField(max_length=50) lname = models.CharField(max_length=50) examdate = models.DateField(auto_now_add =True) answer = models.PositiveSmallIntegerField() def __int__(self): return QuesModel.question[self.question_id] template is home.html: {% … -
Target Specific Members of the User Class
I have a Quote Model where I want to restrict members of the 'rep' dropdown list to a subgroup of Users. How do I restrict the Profile foreign key to only those members with Group 'Account' membership? class CustomerQuote(models.Model): quote_no = models.IntegerField(unique=True, blank=True, null=True, verbose_name="record") date_created = models.DateField(auto_now=False, blank=True, null=True, verbose_name="Date Created") rep = models.ForeignKey(Profile, on_delete=models.DO_NOTHING) ... -
Request Errors with fetch API
I'm trying to send data through a form with just one field to my Django API, then read and use the data received in the API for other things. I don't want to store the data, just use it. This is my react code: const handleSubmit = async (e) => { e.preventDefault(); try{ let res = await fetch(api,{ method: 'POST', headers: {'Content-Type':'application/json'}, body: { url: url, }, }); let resJson = await res.json(); if(res.status === 200){ console.log(resJson) setUrl(""); setMessage("Success"); } else{ setMessage("Error"); } }catch(err){ console.log(err); } }; This is my Django view.py @api_view(['POST']) def eda(request): response = { 'result': 'lalala', 'url':request.POST['body'], 'code': 'success' } return Response(response) I don't understand what's wrong, but I get bad request error or unsupported media type error. -
Using a custom model for Django Admin
I have a custom user model, which an admin model inherits: class User(AbstractBaseUser, PermissionsMixin): ... class Staff(User): is_staff = models.BooleanField( _("staff status"), default=True, help_text=_("Designates whether the user is staff"), ) ... class Admin(Staff): is_admin = models.BooleanField( _("staff status"), default=True, help_text=_("Designates whether the user can log into this admin site."), ) ... As well as a custom backend for authorization class AdminBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(Admin.USERNAME_FIELD) if username is None or password is None: return try: user = Admin._default_manager.get_by_natural_key(username) except Admin.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). Admin().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user ... However, I am unable to log in due to has_permission in admin/sites.py Is there a way to avoid registering a custom site, as that will increase complexity? -
Django : Getting the image URL of elements in a table that has a many-to-one relationship with another table
I have an Event model that is linked to other tables with foreign keys. I want to focus on only the Circuit model: class Event(models.Model): game = models.ForeignKey(Game, verbose_name='Nom du jeu', null=True, on_delete=models.SET_NULL) race_type = models.CharField(verbose_name="Type d'événement", max_length=50, choices=type_course) league = models.ForeignKey(League, verbose_name='Ligue', null=True, on_delete=models.SET_NULL) circuit = models.ForeignKey(Circuit, verbose_name='Circuit', null=True, on_delete=models.SET_NULL) event_date = models.DateTimeField(verbose_name="Date de la course") class Circuit(models.Model): name = models.CharField('Circuit', max_length=120) country = models.CharField('Pays', max_length=120, choices=country_choices) image = models.ImageField(blank=True) I also show here another model that I use in the HTML template : class Game(models.Model): name = models.CharField('Nom du jeu', max_length=100) logo = models.ImageField('Logo', blank=True) And there is the HTML template and the view associated : View : def home(request): games = Game.objects.all() return render(request, 'base_site/home.html', context={'title': 'Accueil', 'games': games}) HTML : {% for game in games %} <h3>{{ game.name }}</h3><br> <div class="row"> {% for event in game.event_set.all %} <div class="col-lg-4 mb-2 mt-2"> <div class="card"> <a href=""><img src="{{ event.image.url }}" class="card-img-top" alt="img-circuit" style="background-color: rgb(255, 255, 255)"></a> <div class="card-body"> <h5 class="card-title"><a href="">{{ event.circuit }}</a></h5> <h6 class="card-title">{{ event.event_date }}</h6> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> </div> <div class="card-footer"> <p>{{ event.ligue }}</p> </div> … -
Changing the CSS on the Django admin page
I am trying to change the admin HTML templates but I don't really now how to find the already created Django templates in the first place. Is there an easy way to find all the templates? Right now I am making new html templates and extending them to Djangos templates. -
Handle divide by zero with aggregated fields in Annotate expression
Currently within the following query, win_rate will always default to 0 unless Lost is 0- in that case, win_rate becomes 100. How do I properly allow division of the aggregated fields while avoiding the division by zero error? top_markets = list(opps .annotate(name=Subquery(Market.objects.filter(id=OuterRef('market'))[:1].values('marketname'))) .order_by('name') .values('name') .annotate(opps=Count('id', filter=Q(datecreated__range=(start_date, end_date))), Won=Count( 'id', filter=Q(winloss='Won') & Q(date_closed__range=(start_date, end_date))), Lost=Count('id', filter=Q(winloss='Lost') & Q( date_closed__range=(start_date, end_date))), Concluded=F('Won') + F('Lost')) ) .annotate( win_rate=Case( When(Won=0, then=0), default=((F('Won')) / \ (F('Won')) + F('Lost'))) * 100 ) -
Django .url not showing image in template
I was getting tired of figuring out how to fix this problem. I checked a lot of different posts and answers but nothing helped me. I have a form where I'm creating new advert. I have file input there for Image. Form is valid and everything works fine, but my problem is that when I want to display my image from Advert model then it's not showing on website.. even the alt text. My template code: {% for advert in adverts %} <img src="{{ advert.get_image }}" alt="test"/> <div class="col-lg-4 col-md-6 col-sm-6"> <div class="mb-4 card"> <div id="second-advert" class="carousel slide"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{{ advert.get_image }}" alt="test"/> </div> </div> My urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('carapp.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My settings.py: STATIC_URL = 'carsearch/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] My models.py: class Advert(models.Model): def get_image(self): if self.featured_image and hasattr(self.featured_image, 'url'): return self.featured_image.url else: return '/path/to/default/image' owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) [...] <-- there's more code featured_image = models.ImageField(null=True, blank=True, default='profiles/user.png', upload_to='adverts/') [...] <-- there's more code def … -
uvicorn, Nginx, and Django Error TypeError: ASGIHandler.__call__() missing 1 required positional argument: 'send'
I am configuring uvicorn, Nginx and Django to run uvicorn and it runs Django, the problem running the uvicorn server gives me the following error: ASGIHandler.call() missing 1 required positional argument: 'send' server { listen 80 default_server; listen [::]:80 default_server; # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Note: You should disable gzip for SSL traffic. # See: https://bugs.debian.org/773332 # # Read up on ssl_ciphers to ensure a secure configuration. # See: https://bugs.debian.org/765782 # # Self signed certs generated by the ssl-cert package # Don't use them in a production server! # # include snippets/snakeoil.conf; root /var/www/html; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name _; location / { include proxy_params; proxy_pass http://unix:/run/backend.sock; } -
Is there a way to reload a Django template screen using the previous request data to an API call?
I built a simple weather app utilizing the OpenWeatherMap API using Python/Django and Django Templates for the client side. I created a refresh button in the <div class="info-grid"> using an <a href="{{ request.get_full_path }}"> and <img> tag, which is intended to refresh to the most current weather information for the currently queried city, but when I click on it, it refreshes the page and shows the weather info for the default city, which I set it to 'Chicago' in views.py. Is there a way to set the refresh button to show the weather info for the currently queried city and not the default city? views.py : def index(request): configure() if 'city' in request.POST: city = request.POST['city'] else: city = 'Chicago' appid = os.getenv('OPEN_WEATHER_API_KEY') URL = 'https://api.openweathermap.org/data/2.5/weather' PARAMS = {'q': city, 'appid': appid, 'units': 'imperial'} r = requests.get(url=URL, params=PARAMS) if r: print(f"==> SUCCESS!: Here's the weather information for {city}. <==") elif city == '': messages.info( request, f'Please enter a city or country.') print( f'!!==> ERROR: User submitted an empty field. <==!!') return redirect('/') else: messages.info( request, f"'{city}' does not exist! Please check your spelling and try searching for a different city or country.") print( f"!!==> ERROR: User entered '{city}'. This value … -
DRF Grant Type Convert Token
I'm trying to implement an authentication system in my Django backend through the Oauth2 protocol. Also, I'm using the drf_social_oauth2 lib. However, I'm having a hard time understanding how I can reproduce the auth system in Postman. Postman offers some auth flows (Grant Types) which greatly facilitates the authentication process. However I came across an authentication flow I've never heard of ( convert_token ). I wish to use the oauth2 system to authenticate using the Facebook Provider, but its not clear for me the flow to validate this in Postman. this is the snippet of code send to validate the access token in react: import axios from 'axios'; import { useHistory } from 'react-router-dom'; const facebookLogin = (accesstoken) => { console.log(accesstoken); axios .post('http://127.0.0.1:8000/auth/convert-token', { token: accesstoken, backend: 'facebook', grant_type: 'convert_token', client_id: '05GYopkyMDxFakgCSuNtpOLrNcyJwU054wZfYBt1', client_secret: 'U3r3rmtff7t52Xa1chfzGf5vtl06zr4PwGbi8sWBcilTKs0YJEm278JPmXbcgMsyYpxYMQbDKFsyjhrzKwDLW8VMfW0ePZmrRuSmssnFPvqjeodYsNTfObTAzxOxZKuH', }) .then((res) => { localStorage.setItem('access_token', res.data.access_token); localStorage.setItem('refresh_token', res.data.refresh_token); }); }; export default facebookLogin; I am expecting to do the same into Postman