Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Swich to light or dark mode on Django?
How can I make a button that when pressed would change my css href between light.css and dark.css I want it without using JavaScript. -
Why this ERROR occurred " ModuleNotFoundError: No module named 'django.ulrs' "?
I was working with Django in urls.py I added a new path that would relate the urls.py in the app to the main urls.py. when I was about to run the server this error occurred and I don't know what is the problem ModuleNotFoundError: No module named 'django.ulrs' and I am pretty sure that Django has a module name django.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('ticketing/', include('Ticketing.urls')) ] -
How do I extend an <li> element?
I have a nav under a header and I want the nav-links to change color and for a white background to be added when hovered over. However, when I hover over the links the white background only shows around the link instead of extending to the most available space as the links are displayed in flex where justify-content: space-around. There are 4 links so I want each link to take up a quarter of the page. How do I do this? HTML: <nav> <ul class="nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Active Listings</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Categories</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Watchlist</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Create Listing</a> </li> </ul> </nav> CSS: nav { background-color: var(--purple); color: #fff; } .nav-link { color: #fff; } li { width: auto; } li:hover { color: var(--purple); background-color: #fff; text-decoration: none; border-radius: 5px; } .nav { display: flex; justify-content: space-around; align-items: center; } -
Limiting API request in django rest framework
I am new to Django | DRF and trying to create a DRF coupon system for course purchases , how can i limit the coupon validity on the basis of number of user used it or some specific time span for ex. only first 50 users can use the code or it will be valid only for next week. (I haven't write the code for it yet that's why i am not able to give you all some insights) I've read a bit of throttling but if i am not wrong it only limits on the basis of rate Any reference will be really helpful. Thanks ! -
forms fields returning None
I have form, of which travel_date and max_amt fields returning none after submitting the form from template code for ref: forms.py class GetQuery(forms.Form): origin = forms.CharField(max_length=30, widget=forms.TextInput( attrs={'type': 'text', 'id': 'org', 'name': 'origin', 'placeholder': 'origin code'})) destination = forms.CharField(max_length=30, widget=forms.TextInput( attrs={'type': 'text', 'id': 'dst', 'name': 'destination', 'placeholder': 'destination code'})) travel_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date', 'name': 'date'})) max_amt = forms.CharField(max_length=6, widget=forms.NumberInput( attrs={'type': 'number', 'id': 'amt', 'name': 'amount', 'placeholder': 'Enter Price Range'})) Views.py def home(request): if request.method == "POST": origin, destination, date, amount = request.POST.get('origin'), request.POST.get('destination'), request.POST.get('date'), request.POST.get('amount') print(origin, destination, date, amount) IC = AC.objects.all().order_by('-pk') form = GetQuery return render(request, 'index.html', context={'IC':IC, 'form': form}) template <form name="TravelQuery" method="post" novalidate="novalidate"> {% csrf_token %} <div class="row"> <div class="col-6"> {{ form.origin|as_crispy_field }} </div> <div class="col-6"> {{ form.destination|as_crispy_field }} </div> <div class="col-6"> {{ form.max_amt|as_crispy_field }} </div> </div> {{ form.travel_date|as_crispy_field }} <div class="col-md-12 text-right"> <button type="submit" value="submit" class="btn btn-primary primary-btn text-uppercase">Send Message</button> </div> </form> getting values for origin and destination but not for travel_date and max_amt. -
django-import-export | issue in importing data to database | ValueError: Field 'id' expected a number but got ''
I am using Django-import-export for importing data but facing an error given below. Code settings i tried to import data to postgresql database by django-import-export class MemberResource(resources.ModelResource): Brand=Field() class Meta: model = model fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') export_order=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') def dehydrate_Brand(self, obj): return str(obj.Brand.title) class modelAdmin(ImportExportModelAdmin): resource_class = MemberResource list_display=['id','title','Model_code','Chipset','chipset_description','Brand','categories'] search_fields = ['title','Model_code','Chipset',] fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat') admin.site.register(model,modelAdmin) and got below error also attached the image where i exported the data from app and then edited the same and tried to import and stuck with below error. [Line number: 1 - Field 'id' expected a number but got ''. 2, f9, sd, gf, kjkj, images/sample_3pahsfV.jfif, 1, 1 Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in _get_ rel_obj = self.field.get_cached_value(instance) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache\[cache_name\] KeyError: 'Brand' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\_init_.py", line 1988, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 707, in import_row diff = self.get_diff_class()(self, original, new) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 241, in _init_ self.left = self._export_resource_fields(resource, instance) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in _export_resource_fields return \[resource.export_field(f, … -
submit multiple forms in django using custom html form
I have custom forms in the page suprated across the page here is my first form <form name="profile_image" class="edit-phto" method="POST" enctype="multipart/form-data"> <i class="fa fa-camera-retro"></i> <label class="fileContainer"> Edit Display Photo <input name="profile_image" value="" type="file" /> </label> </form> for profile picture and i have another form for cover picture <form name="cover_image" class="edit-phto" enctype="multipart/form-data"> <i class="fa fa-camera-retro"></i> <label class="fileContainer"> Edit Cover Photo <input name="cover_image" type="file" /> </label> </form> and another form for data :) <form method="post" id="infoform" enctype="multipart/form-data"> {% csrf_token %} . . . . <div class="submit-btns"> <button type="button" class="mtr-btn"><span>Cancel</span></button> <button type="submit" class="mtr-btn" name="update"><span> Update</span></button> </div> and i have a form for search <div class="searched"> <form method="post" class="form-search"> <input type="text" placeholder="Search Friend"> <button data-ripple><i class="ti-search"></i></button> </form> </div> i just want to submit the 2 images forms and info forms when i click update button is there a way to do sachthing in django without using form.as_p and stuff like that -
Best Django Analytic service or how do i implement a good analytic dashboard
Im new to Django and im trying to build a analytic dashboard for my Django e-commerce project that tracks income, expenses and popular items(items with high demand) and I've been surfing but I cant find how to do it. If anyone has any service that they recommend or any tips on how to implement it ill appreciate it -
Why three methods(get,put,delete) are activated for each of my endpoints? Django Rest Framework
Why three methods(get,put,delete) are activated for each of my endpoints? Django Rest Framework -
django how can i a selected field, as label render
Im create with: class FooForm(forms.ModelForm): class Meta: model = foo fields = '__all__' a auto form of the model. this works fine. When i now render the fields with: {% for field in formfields %} {{ field}} {% endfor %} create me this a field for the foreignkey, like a selectfield: <select name="foo" required id="id_foo"> <option value="">---------</option> <option value="1">A</option> <option value="2" selected>B</option> <option value="3">C</option> <option value="4">D</option> I want but like to display only the selected option like a label: A -
IntelliJ IDEA auto import doewn't work for Python
I have using IntelliJ IDEA for php developement and it works without a issue. I have just started doing some Django coding and I encountered this issue where autocomplete doesn't work for imports. I'm using Python 3.9 with Django 4.0.6 and I use pipenv for virtual environment. I'm trying to do some basic imports like importing HttpResponse from django.http. I expect the IDE to suggest the import as I'm typing (like for php) but it doesn't. for it to work I have to press control+space 2 times and then it shows the suggestions (If I just pres it 1 time it says "No suggestions") or I can type everything then press option+return and it suggests to import it then. Auto Import setting for python is like this: Code Completion setting doesn't have a Python section but the general area is set up like this: Project setting seems to be correct and does have the django module: and this is my .iml file in the .idea folder: <?xml version="1.0" encoding="UTF-8"?> <module type="PYTHON_MODULE" version="4"> <component name="FacetManager"> <facet type="django" name="Django"> <configuration> <option name="rootFolder" value="$MODULE_DIR$" /> <option name="settingsModule" value="django_app/settings.py" /> <option name="manageScript" value="manage.py" /> <option name="environment" value="&lt;map/&gt;" /> <option name="doNotUseTestRunner" value="false" /> <option name="trackFilePattern" … -
Before Sving the page Show an Alert Message Django Script
I am trying to create an alert message before saving the page, i tried to it Django Forms , But did not worked def clean(self): cleaned_data = super(CountryForm, self).clean() cc_myself = cleaned_data.get("registrations") subject = cleaned_data.get("calendar") if cc_myself and subject: if "help" not in subject: raise forms.ValidationError( "You can edit the values" ) -
How to properly catch POST request in a Django serializer when using the JSON Web token authentication?
I customized the AUTH_USER_MODEL variable in settings.py to implement JSON Web Token authentication in Django, and everything works perfectly to login as superuser in the admin section. However, when I try to register a new user with the REST API, the line request.data.get('user', {}) in the serializer returns an empty dictionary, so I need to convert the object of type QueryDict into a Dict. Then I need to unlist the dictionary's values to finally have valid data. I'm afraid there is something wrong in my code, what is the proper way to do that ? I followed the tutorial from Thinkster here. views.py from rest_framework import status from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.views import APIView from authentication.serializers import RegistrationSerializer class RegistrationAPIView(APIView): permission_classes = (AllowAny,) serializer_class = RegistrationSerializer def post(self, request): # user = request.data.get('user', {}) # <- returns {} user = dict(request.data) user = {k:v[0] for k,v in user.items()} serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) settings.py AUTH_USER_MODEL = 'authentication.User' AUTHENTICATION_BACKENDS = [ 'graphql_jwt.backends.JSONWebTokenBackend', 'django.contrib.auth.backends.ModelBackend', ] GRAPHQL_JWT = { "JWT_ALLOW_ARGUMENT": True, } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'authentication.backends.JWTAuthentication', ] } -
How do I view movies in descending order of average score? django
What we want to achieve. I want to display the score (stars) of a movie in descending order. Present condition The tmdb API is used to retrieve movie information. And the model movie and TV have only ID and stars(score). From here, only those with stars are returned to html. I want to ask a question. And if score is selected, how can I make it appear in descending score order? data = requests.get (f "https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US"). Now you can get the information of tv. def index(request): movie = reversed(Movie.objects.order_by('stars')) tv = reversed(TV.objects.order_by('stars')) context = { "movie": movie, "tv" : tv, } return render(request, 'Movie/index.html', context) class Movie(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_movie.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class TV(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_tv.objects.filter(tv_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class … -
Django: How to save javascript auto-increment to django database?
I am incrementing a value from my database evey 3.5 sec using javascript, but the value that i am incremeting is coming dynamically from the database, now i want to save the newly incremented value to the database as the increment keeps going, i don't know how to achieve this using django and javascript. When i refresh the page, the value resets to the default value that i have in my database and doesn't update the value with the new increments <span id="generated">{{total_points}}</span> <!-- This is the js doing the increment function --> <script> var i = {{total_points}}; function increment() { i++; document.getElementById('generated').innerHTML = `₦` + Number(i).toLocaleString('en') + `.00`; } setInterval('increment()', 3140); </script> how do i save the new increments to the database? Do i need to provide my models.py? -
How to make divisions go on a new line? html/css
So, I want maximum of 3 div's per row, so when I use "for" loop after 3 instances it would automatically go to a new line. I have very little knowledge in js, so it'll be better if you can suggest me something not connected with it. Thank you in advance. (Making this template for my first django project). .main-section{ background: white; text-align: center; border: solid 1px #D1BEA8; } .book-list-main{ display: table; table-layout: fixed; border-spacing: 30px; } .single-book{ display: table-cell; width: 310px; height: 400px; margin: 0 20px 20px 10px; grid-column-start: 1; border: solid 1px #D1BEA8; height: fit-content; } .img-description-container{ display: flex; } .single-book h1{ font-size: 20px; } .img-description-container img{ max-width: 180px; max-height: 240px; float: left; } .img-description-container p{ float: right; font-size: 12px; overflow-y: scroll; margin-top: 50px; } .author-display{ display: flex; flex-direction: column; } .author-display span{ font-size: 14px; margin-top: 30px; background-color: #f1efe5; } .votes-total { position: relative; } .votes-total:before { content: attr(data-hover); visibility: hidden; opacity: 0; width: 60px; color: black; background-color: aliceblue; text-align: center; border-radius: 5px; padding: 5px 0; position: absolute; font-size: 11px; z-index: 1; left: 0; top: -110%; } .votes-total:hover:before { opacity: 1; visibility: visible; } .single-book-footer{ margin-top: 15px; margin-left: 17px; display: flex; flex-direction: row; } .single-book-footer button{ height: 30px; … -
CSS file references a file which could not be found. (Fieldsets forms and Heroku)
I am using fieldsets for my django forms. Everything works fine on local. I wanted to uploaded onto Heroku and started running into problem. When running "python manage.py collectstatic", I am getting the following error: The CSS file 'forms_fieldset\css\main.css' references a file which could not be found: forms_fieldset/img/sorting-icons.svg The message is correct. The file forms_fieldset/img/sorting-icons.svg is not mentioned in main.css. I suppose there is two questions: How does it know a file does not exist, if it actually not mentioned anywhere? How and where can I add this file? Below is my settings.py, just in case someone wants to look at it: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "crispy_forms", 'main.apps.MainConfig', 'register.apps.RegisterConfig', 'import_export', 'forms_fieldset', ] ... STATIC_URL = 'static/' #IMAGE STUFF# MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') #Staticfiles_storage to make it compatible with Heroku SATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' #storing static files VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"),) -
Customizing authentication backend for multi users in Django
So my question is that you have a custom user 'Account' and I'm trying to use Loginview but with only one specific backend but the class does not care about the value passed. from django.contrib.auth import views as auth_views from .lists import ProjectCreateView , ProjectUpdateView , ProjectDeleteView class ClientLogin(auth_views.Loginview): def form_valid(self, form): """Security check complete. Log the user in.""" auth_login(self.request, form.get_user(),'CREA.models.ClientBackend') return HttpResponseRedirect(self.get_success_url()) urlpatterns = [ path('', ClientLogin.as_view(template_name='authentification/client_login.html', redirect_authenticated_user=True,next_page='client-home'), name='client-log-in'), NB: note that the backend works fine if it's the only one specified in the settings but other than that the loginview use all backends one by one, and yes I know that this is the default behaviour but then whats the point of this variable in auth_login here is the buld in function in django : def login(request, user, backend=None): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = "" if user is None: user = request.user if hasattr(user, "get_session_auth_hash"): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: if _get_user_session_key(request) != user.pk or ( session_auth_hash and not constant_time_compare( request.session.get(HASH_SESSION_KEY, … -
django import_export | data not exported from database
I am using Django-import_export for exporting data. I have used the code given below that's not working correctly. It exported only dehydrated data instead of given fields. class MemberResource(resources.ModelResource): Brand=Field() class meta: model = model fields=('title','Brand') def dehydrate_Brand(self, obj): return str(obj.Brand.title) class modelAdmin(ImportExportModelAdmin): resource_class = MemberResource list_display=['title','Model_code','Chipset','chipset_description','Brand','categories'] search_fields = ['title','Model_code','Chipset',] fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat') admin.site.register(model,modelAdmin) -
in decorator assert not existing_data, "swagger_auto_schema applied twice to method"
I have added three input fields as headers but coming swagger_auto_schema applied twice to method issue and other one when I'm adding one swagger_auto_schema with given header input field than working fine where as when I'm adding three swagger_auto_schema with adding thier object than getting this error This is my code from rest_framework.generics import GenericAPIView from drf_yasg.utils import swagger_auto_schema from drf_yasg import openapi class ProductDataView(GenericAPIView): serializer_class = ProductSerializer permission_classes = (IsValidConsumer,) categories = openapi.Parameter('categories', in_=openapi.IN_HEADER, description='categories', type=openapi.TYPE_STRING, required=True) productName = openapi.Parameter('product_name', in_=openapi.IN_HEADER, description='product_name', type=openapi.TYPE_STRING) CustomerName = openapi.Parameter('customer_name', in_=openapi.IN_HEADER, description='customer_name', type=openapi.TYPE_STRING) @swagger_auto_schema(manual_parameters=[productName]) @swagger_auto_schema(manual_parameters=[categories]) @swagger_auto_schema(manual_parameters=[CustomerName]) -
how to pass 2 pks of different models in the same url django
how do i add primary keys of 2 different models of post model and comment model in the same url of editing comments when im adding 2 int pks in the same url it shows an error and when im giving 1 custom name then it doesnt work views.py class EditCommentView(UpdateView): model = Comment form_class = EditCommentForm template_name = "edit_comment.html" urls.py urlpatterns = [ path("post/<int:pk>/comments/", login_required(CommentsView.as_view(), login_url='signin'), name="comments"), path("post/<int:pk>/comments/add/", login_required(AddCommentView.as_view(), login_url='signin'), name="add-comment"), path("post/<int:pk>/comments/<int:pk>/edit/", login_required(EditCommentView.as_view(), login_url='signin'), name="edit-comment"), ] template {% extends "base.html" %} {% block content %} <section class="text-gray-600 body-font overflow-hidden"> <div class="container px-5 py-24 mx-auto"> <div class="flex flex-col text-center w-full mb-12"> <h1 class="sm:text-3xl text-2xl font-medium title-font mb-4 text-gray-900">Comments</h1> <p class="lg:w-2/3 mx-auto leading-relaxed text-base"> <a class="text-indigo-500 inline-flex items-center mt-4" href="{% url 'add-comment' post_id %}">Add Comment </a> </p> </div> <div class="-my-8 divide-y-2 divide-gray-100"> {% for comment in object_list %} <div class="py-8 flex flex-wrap md:flex-nowrap"> <div class="md:w-64 md:mb-0 mb-6 flex-shrink-0 flex flex-col"> <!-- <span class="font-semibold title-font text-gray-700">CATEGORY</span> --> <span class="mt-1 text-gray-500 text-sm">{{comment.date_created}}</span> </div> <div class="md:flex-grow"> <h2 class="text-2xl font-medium text-gray-900 title-font mb-2">{{comment.user.username}}</h2> <p class="leading-relaxed">{{comment.body}}</p> <a class="text-indigo-500 inline-flex items-center mt-4" href="{% url 'edit-comment' post_id comment.id %}"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-square" viewBox="0 0 16 16"> <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 … -
Show an Alert Message before saving the page Django
I am trying to create an alert message before saving the page, i tried to it Django Forms , But did not worked def clean(self): cleaned_data = super(CountryForm, self).clean() cc_myself = cleaned_data.get("registrations") subject = cleaned_data.get("calendar") if cc_myself and subject: # Only do something if both fields are valid so far. if "help" not in subject: raise forms.ValidationError( "You can edit the values" ) -
DRF Add multiple annotated fields to nested serializer
In my queryset i have few annotate fields. I want group those fields to nested serializer. For example views.py class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all().prefetch_related( Prefetch('comments', queryset=Comment.objects.filter(parent__isnull=True).order_by('-pub_date') .annotate(likes=Count('votes', filter=Q(votes__choice=True)), dislikes=Count('votes', filter=Q(votes__choice=False))))) So there is two additional fields 'likes', 'dislikes' serializers.py class CommentVoteSerializer(serializers.Serializer): likes = serializers.IntegerField(source='comments.likes') dislikes = serializers.IntegerField(source='comments.dislikes') class Meta: fields = ['likes', 'dislikes'] class CommentSerializer(serializers.ModelSerializer): rating = CommentLikesSerializer(read_only=True, many=True) class Meta: model = Comment fields = ['id', 'text', 'pub_date', 'rating'] I tried different ways but can't understand how to fix it. Thanks for help -
convart raw sql to django query
I want to convert qs = Category.objects.raw('SELECT y.id,y.name,y.parent_id FROM core_category y INNER JOIN (SELECT name,parent_id, COUNT(*) AS CountOf FROM core_category GROUP BY name,parent_id HAVING COUNT(*)>1 ) dt ON y.name=dt.name AND y.parent_id=dt.parent_id') this raw sql to django sql query -
spotify api "player/currently-playing" enpoint is not return currently playing song data
I am trying to get data about a song playing on one of my devices from the spotify API. I have created a view that fetches data from the API and part of it looks like this: class Song(viewsets.ModelViewSets): .... room_code = request.data['room_code'] room = Room.objects.filter(code=room_code)[0] host = room.host endpoint = 'player/currently-playing' response = execute_spotify_api_request(host, endpoint) item = response.get('item') duration = item.get('duration_ms') progress = response.get('progress_ms') album_cover = item.get('album').get('images')[0].get('url') return Response(response, status=status.HTTP_200_OK) The execute_spotify_api_request(host, endpoint) is a utility function and it looks like this: def execute_spotify_api_request(session_id, endpoint, post_=False, put_=False): tokens = get_user_tokens(session_id) headers = {'Content-Type': 'application/json', 'Authorization': "Bearer " + tokens.access_token} if post_: post(BASE_URL + endpoint, headers=headers) if put_: post(BASE_URL + endpoint, headers=headers) response = get(BASE_URL, {}, headers=headers) try: return response.json() except: return {'error': 'Could not retrieve a response'} The full url from which im fetching is ""https://api.spotify.com/v1/me/player/currently-playing" The problem is with the response that im getting from the API, the response is not an error but data that im not expecting to get. Im getting a response that looks like this: response = { "display_name": "Tanatswamanyakara", "external_urls": { "spotify": "https://open.spotify.com/user/dlnsysel6bndktbvduz6cl79w" }, "followers": { "href": null, "total": 0 }, "href": "https://api.spotify.com/v1/users/dlnsysel6bndktbvduz6cl79w", "id": "dlnsysel6bndktbvduz6cl79w", "images": [], "type": "user", "uri": "spotify:user:dlnsysel6bndktbvduz6cl79w" } I …