Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(unicode error) 'utf-8' codec can't decode byte 0xf3
I'm using django 5.0.8 and python 3.11, so in my view i use this: context = RequestContext(request, { 'title':'sómething', 'formLogin': formLogin }) As you can see i pass string with 'ó' value, when i try to run my project gives me the error '(unicode error) 'utf-8' codec can't decode byte 0xf3' this happen with any special characters for what i know using '# -- coding: utf-8 --' at first in my view solve this, but not now, what can i do? -
How to reload the current page with a different html template after a Task completes in Django?
I'm working on a Django project where I need to handle a task that runs in the background. Once the task is completed, I want to reload the current page, but I also need it to load a specific HTML template on that same URL. Currently, I'm using AJAX to poll the status of the task, and once it’s completed, I receive a JSON response from the server indicating the task's completion. My goal is to reload the current page when the task is done, so the user can see the updated content. I want that if the user visits the page later or deletes or reloads the tab the new template is what is loaded and not the old one. Here's my django view: @csrf_protect def initiate_transcription(request, session_id): file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') try: transcribed_doc = TranscribedDocument.objects.get(id=session_id) except TranscribedDocument.DoesNotExist: return JsonResponse({'status': 'error', 'message': 'Document not found'}, status=404) if request.method == 'GET': if not file_name or not file_path: return redirect(reverse('transcribeSubmit')) if request.method == 'POST': if not file_name or not file_path: return redirect(reverse('transcribeSubmit')) else: try: if transcribed_doc.state == 'not_started': transcribed_doc.state = 'in_progress' transcribed_doc.save() audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') task = transcribe_file_task.delay(file_path, audio_language, output_file_type, 'ai_transcribe_output', session_id) return JsonResponse({'status': 'success', 'task_id': … -
Best practices for enum with django models and migrations
I have a django model with a field that uses a enum for it's choices tuple like this: VERSION_CHOICES = tuple( (v.value, v.value) for v in ForwardsUpdateEventSensitivityVersion ) version = models.CharField( max_length=max(len(s[0]) for s in VERSION_CHOICES), choices=VERSION_CHOICES, ) What is the best practice for writing the accompanying migration? Using the enum directly like this: models.CharField( choices=[ tuple( (v.value, v.value) for v in ForwardsUpdateEventSensitivityVersion ) ], ) Or hardcoding the values like this: models.CharField( choices=[("V1", "V1"), ("V2", "V2")], ) -
Somebody know how to add the anchor plugin on CKEDITOR5?
I am trying to add anchors on CKEDITOR5, but the editor automaticaly removes de 'id' atributte when i exit the text source mode, i tried to find a anchor plugin for ckeditor5, but i don find nothing that works on django. <p> <a href="#bottom">go bottom</a> </p> <p> &nbsp; </p> <p> &nbsp; </p> <p id="bottom"> bottom </p> -
raise self.model.DoesNotExist( django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist
I am implementing google authentication in my website but whenever I run my code I got this error. Internal Server Error: / Traceback (most recent call last): File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\Documents\tournament-web\Xoriva\loginpage\views.py", line 6, in home return render(request, "home.html") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\shortcuts.py", line 25, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\backends\django.py", line 107, in render return self.template.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\base.py", line 171, in render return self._render(context) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\base.py", line 1008, in render return SafeString("".join([node.render_annotated(context) for node in self])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\base.py", line 969, in render_annotated return self.render(context) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\template\library.py", line 237, in render output = self.func(*resolved_args, **resolved_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\allauth\socialaccount\templatetags\socialaccount.py", line 21, in provider_login_url provider = adapter.get_provider(request, provider) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\allauth\socialaccount\adapter.py", line 214, in get_provider app = self.get_app(request, provider=provider, client_id=client_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\allauth\socialaccount\adapter.py", line 297, in get_app apps = self.list_apps(request, provider=provider, client_id=client_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\allauth\socialaccount\adapter.py", line 242, in list_apps db_apps = SocialApp.objects.on_site(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\allauth\socialaccount\models.py", line 34, in on_site site = get_current_site(request) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rahul\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\contrib\sites\shortcuts.py", line … -
Issue with Django translation not reflecting in the admin interface
I'm working on enabling Swedish translations in a Django project using the standard i18n/l10n setup, but I can't get the translated strings to appear in the admin interface. I've set up the LOCALE_PATHS, created .po and compiled .mo files, and added 'sv' to LANGUAGES in settings.py, but the admin is still showing English strings. What am I missing? I've already run python manage.py compilemessages, ensured that the .mo files exist, and tried clearing the cache, but the admin interface still defaults to English. Has anyone encountered this before? Is there something I might be missing in the configuration or setup? -
Django migrations operations inside RunPython code
I'm working with data migrations in django, and at some point, I'll have to run migrations.RunPython. The point is that I wish I could execute migrations operations(AddField, AlterField) under certain conditions. For example: def forward_migration(apps, schema_editor): if some_condition: migrations.AddField(...) class Migration(migrations.Migration): dependencies = [ ('some_app', '0002_auto_...'), ] operations = [ migrations.RunPython(forward_migration) Thanks in advance. -
Sending Apple Push Notifications to Wallet Passes for different PassTypeID
i have a webapp that is able to create apple wallet passes for iOS. Process more or less looks like this: User provides his Apple Pass ID and certificate from apple developer, based on that cert i am creating wallet passes that i can send to devices, then devices register to my webServiceURL. Now i have tested this app while creating the passes from my Apple Pass ID and while using my APNs key from the same developer account and everything works great. What im looking for now is how to send push notifications to devices that have passes with different Apple Pass ID (so from user apple pass ID) with my APNs key. Apps like PassKit etc. can send those notifications while not requesting user to provide his APNs key, maybe there is something i fundamentally dont understand about this process? Im using aioapns library for python and when i try to push notify pass made with PassTypeID from different apple developer account, if i use that PassTypeID as topic with keys from my developer accound i get TopicDissalowed, and when i use my PassTypeID as topic, device is not notified. -
My css styles don't connect to my django-written website
Some styles were connected without any problems, but I managed to make only one section, as they stopped connecting and my entire site began to look like a document in word I have already searched for similar problems here, tried the solutions given; I also searched for how to connect styles, etc. Unfortunately, I did not find a solution to my problem, so I am writing here Base.html {% load static %} <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock %}</title> {% block css %} <link rel="stylesheet" href="{% static 'css/_normalize.css' %}"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> {% endblock %} </head> index.html {% extends './base.html' %} {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'css/main.css' %}"> {% endblock %} {% block title %} Главная {% endblock %} {% block content %} <section class="hero"> <div class="container hero__container"> <div class="hero__content"> <div class="hero__text"> <h1 class="title hero__title"> Центр подбора лечения от&nbsp;алкоголизма, наркомании и&nbsp;других зависимостей </h1> <h4 class="title hero__subtitle"> Мы&nbsp;приходим на&nbsp;помощь в&nbsp;самых нелегких ситуациях и&nbsp;точно знаем как можем помочь и&nbsp;пациенту, и&nbsp;его близкому окружению. </h4> </div> <button class="btn btn-reset hero__btn"> <a href="#" class="link-reset hero__link">Бесплатная консультация</a> </button> </div> <div class="hero__image"> <img src="{% static 'images/hero/hero-img.png' %}" … -
Can't send files to ChatConsumer in Django Channels
I'm having an issue with sending files to a handler in ChatConsumer using Django Channels. I have two consumers, ChatConsumer and GroupChatConsumer, for handling direct messages and group messages. I want to send files to ChatConsumer or GroupChatConsumer based on whether a group exists or not. If the group doesn't exist then file should go to ChatConsumer I'm sending the files using channel_layer.group_send through views. Keep in mind I have the same handler name in ChatConsumer and GroupConsumer but despite changing those the issue persists What i have tried: Added print statements right after group_send to confirm if they execute without any error and they do! I also added logging inside ChatConsumer to see if any file or message is recived but there isn't! Ensured if the websocket connections are active and they are! So how can I verify if a message is successfully sent to ChatConsumer? Why is the consumer not receiving any messages? My code: https://github.com/Kioshi5581/djchat -
Django Debug Toolbar is not showing
After setting all the configuration i still cant see the toolbar. P.S. some of ther other not related to the problem code were removed to save space What I Did python -m pip install django-debug-toolb settings.py Also tried adding fix for set content type of js files in Django import mimetypes mimetypes.add_type("application/javascript", ".js", True) from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'playground', "debug_toolbar", ] MIDDLEWARE = [ "debug_toolbar.middleware.DebugToolbarMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'storefront.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'storefront.wsgi.application' STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' INTERNAL_IPS = [ "127.0.0.1", ] urls.py from django.conf import settings from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns += path('__debug__/', include(debug_toolbar.urls)), after all these changes i just ran python manage.py runserver or F5 And after all these steps i still dont see the toolbar -
Django: Html select with onchange action (without using form) and pure Javascript: redirect with code 200 but page not loaded
I have a select box in my template that reacts on changes with the onchange function that sends the selected value to the Django view. The view gets the required data from the database and should display them. main.html {% block content %} <select class="form-select form-select-lg mb-3 categorySelect select" name="categorySelect" aria-label="Select category" onchange="getSelectedId(value)"> <option value="None">Select category</option> <option value="all">All</option> <option value="cat1">Category 1</option> <option value="cat2">Category 2</option> </select> {% endblock %} select.js function getSelectedId(selectedValue) { const value = selectedValue; const endpoint = "/all/select"; fetch(endpoint + "?select_id=" + value) .then() .then(response => { }) } views.py def select(request): select_id = request.GET.get("select_id", "None") print(select_id) if select_id.__contains__('None'): return render(request, "home/main.html" ) elif select_id.__contains__('all'): return redirect(reverse('all:probe_list')) elif select_id.__contains__('cat1'): selected = "Category 1" config = RequestConfig(request) resultTable = AllProbesTable(Probe.objects.filter(category = "cat1")) config.configure(resultTable) return render(request, 'all/selectResults.html', {'table':resultTable, 'selected': selected}) I get the correct select_id in the view and the I get a 200 from the redeirect but the page is not changing (similar to This question). I understand that I need to add a reload such as "location.reload()". I added this to the template I am redirecting to but this did not work. Is there any way to trigger a reload or is there another way to implement a … -
Is Enumerating Through Multiple Categories in API Tests a Good Practice? Alternatives for View Testing?
I'm currently writing tests for my Django application using pytest and pytest-django. One of my tests involves creating multiple category instances and verifying that they are correctly listed in the API response. Here’s a snippet of the test: @pytest.mark.django_db def test_auth_user_can_list_categories(auth_client, category_factory): categories = category_factory.create_batch(5) url = reverse("category-list") response = auth_client.get(url) assert response.status_code == 200 for i, category in enumerate(categories): assert response.data[i]["id"] == category.id assert response.data[i]["name"] == category.name In this test, I’m creating 5 distinct categories and then using enumerate to loop through them to verify that each category is correctly listed in the API response. I’m wondering if this approach of enumerating through the categories to match them with the API response is considered a good practice. Are there any better or more efficient ways to test this scenario? Specifically, are there alternative strategies for view testing that could offer more robust or scalable solutions? I’d appreciate any advice or best practices on how to improve this test or alternative methods to achieve the same results. -
Background-image in CSS url blocked by Opaque Response Blocking
I use a background-image like this: <style> .bg-image { background-image: url("{{ instance.background.url }}"); } </style> but the request gets blocked A resource is blocked by OpaqueResponseBlocking. Displaying the image the 'normal' way with <img src="..."> works perfectly. I tried setting a header in CORS-Configuration like: Content-Type: text/css but that did not change anything. I did specify the origin domain and allowed GET, PUT, DELETE, POST and HEAD. -
Django Session variables not visible after login
I am developing a hospital site. patients are allowed to login and book appointment. When a patient logs in, a sessions is initiated and saved. Again, I debugged, by adding a print statement after saving the sessions in the login view and its good, but when i try to book an appointment, then i print the session variables, they are empty. Could anyone please help me on this.... I would really appreciate. Note: My frontend is built with Next.js and am adding credentials='include' on my request. Also the cookies are set well in my browser with the key: sessionid and its value. const response = await fetch( "http://127.0.0.1:8000/bookings/book-appointment/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(appointmentData), credentials: "include" } ); @csrf_exempt def login_view(request): if request.method == 'POST': try: data = json.loads(request.body) email = data.get('email') password = data.get('password') # Fetch the user from the database user = Patient.objects.filter(email=email).first() # Check if user exists and password is correct if user and user.check_password(password): # Handle 2FA if enabled if user.enable_2fa: generate_and_send_2fa_code(user) return JsonResponse({ 'success': True, 'message': '2FA code sent', 'user_id': user.id, 'email': user.email, 'requires_2fa': True }) # Set session expiry time request.session.set_expiry(2 * 60 * 60) # 2 hours # Log … -
Django error on forms when running makemigrations
I'm getting the following error when trying to make migrations for my models. This is against a clean DB so it is trying to generate the initial migrations. File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/LifePlanner/urls.py", line 20, in <module> from . import views File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/LifePlanner/views.py", line 7, in <module> from .forms import AppUserForm, IncomeSourceForm, AccountForm, SpouseForm, DependentForm File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/LifePlanner/forms.py", line 32, in <module> class AccountForm(forms.ModelForm): File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/ProjectEnv/lib/python3.11/site-packages/django/forms/models.py", line 312, in __new__ fields = fields_for_model( ^^^^^^^^^^^^^^^^^ File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/ProjectEnv/lib/python3.11/site-packages/django/forms/models.py", line 237, in fields_for_model formfield = f.formfield(**kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/ProjectEnv/lib/python3.11/site-packages/django/db/models/fields/related.py", line 1165, in formfield "queryset": self.remote_field.model._default_manager.using(using), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'using' This is the form in my forms.py: class AccountForm(forms.ModelForm): class Meta: model = Account fields = ['account_name','owner','account_provider','balance'] labels = {'account_name': 'Name','account_provider': 'Account Provider','balance': 'Balance','owner': 'Owner'} And here are the relevant Models in models.py: class Projectable(models.Model): class Meta: abstract = True def project_annual_values(self, years): raise NotImplementedError("Subclasses should implement this method.") def project_monthly_values(self, months): raise NotImplementedError("Subclasses should implement this method.") class AccountProvider(models.Model): name = models.CharField(max_length=64) web_url = models.CharField(max_length=256) login_url = models.CharField(max_length=256) logo_file= models.CharField(max_length=64) def __str__(self): return f"{self.name}" class Account(Projectable): account_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=15, decimal_places=2) owner = models.ForeignKey(Agent, on_delete=models.CASCADE) account_provider = models.ForeignKey(AccountProvider, on_delete=models.SET_NULL) def get_balance(self): return self.balance def get_account_type(self): … -
order_by combined column in django
I have two models who inherit from another model. Example: class Parent(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, verbose_name="ID") class A(Parent): name = models.CharField(max_length=255, verbose_name="Name") class BProxy(Parent): target = models.OneToOneField('B', on_delete=models.CASCADE) class B(models.Model): name = models.CharField(max_length=255, verbose_name="Name") My query currently looks like this: Parent.objects.all() In my serializer, I check which subclass the parent object is (hasattr(obj, 'a')) and then use either name = obj.a.name or name = obj.b.target.name for the serialized data. But now I would like to sort the queryset for the output. Normally I would use Parent.objects.all().order_by('name') here. But the name is in the subclasses. Would it be possible to combine the “name” columns of the two subclasses and then sort by them? Or is there another solution? -
Django s3 bucket upload with out admin static css and js
Is it possible to upload the files into s3 buckets in Django without uploading default django admin css, js files? all files are getting uploaded; but i need only uploaded files in S3 buckets. Is there any work around for this? Any changes to settings file that will help to achieve this ? -
How do I create Stripe-like DB ID's for Django models?
Core problem I'm trying to solve: I want to have ID's on my database models that are similar to Stripe's (i.e. of the form aaa_ABCD1234 where the ABCD1234 part is a ULID and the aaa_ part is effectively the table name (or a shortened version of it)). This feature has saved me a ton of time in debugging Stripe integrations and I'd love for users of my systems to be able to have those same benefits. However, I know taking the nieve approach and just a string as a primary key on a table is terrible for performance (mostly indexes and consequently joins as I understand it) so I want to take advantage of the built in UUID datatype in the DB to store only the ABCD1234 part in the DB and not store the aaa_ part since that will be identical for all rows in that table. Where I stand today I'm currently thinking of doing this as follows: Have a "private" field on the DB model (call it _db_id?) that is the UUID and technically the primary key on the model in the DB. Have a GeneratedField that takes the above private field and prepends the table prefix … -
How to convert query string parameters from Datatables.js, like columns[0][name] into an object in Python/Django?
I'm using DataTables.js and trying to hook up server-side processing. I'm using Django on the server. Currently, the data to Django looks like: {'draw': '1', 'columns[0][data]': '0', 'columns[0][name]': 'Brand', 'columns[0][searchable]': 'true', 'columns[0][orderable]': 'true', 'columns[0][search][value]': '', 'columns[0][search][regex]': 'false', 'columns[1][data]': '1', 'columns[1][name]': 'Sku', 'columns[1][searchable]': 'true', 'columns[1][orderable]': 'true', 'columns[1][search][value]': '', 'columns[1][search][regex]': 'false', 'columns[2][data]': '2', 'columns[2][name]': 'Name', 'columns[2][searchable]': 'true', 'columns[2][orderable]': 'true', 'columns[2][search][value]': '', 'columns[2][search][regex]': 'false', 'order[0][column]': '0', 'order[0][dir]': 'asc', 'order[0][name]': 'Brand', 'start': '0', 'length': '10', 'search[value]': '', 'search[regex]': 'false', '_': '1725412765180'} (as a dictionary) However, there's a variable number of columns and order values that might come through. So I'd like to convert all of this into a few key variables: start length search value search regex draw array/list of column objects array/list of order objects But I don't know a lot of python -
JWT token claims in Django Rest Framework
I am using rest_framework_simplejwt, and would like to add extra information to the access token returned for authorization purposes. Following along with https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html I am able to modify the access token. However I want to be able to add a claim based on the initial POSTed login. For example: curl -X POST -H 'Content-type: application/json' -d '{"username": "user1", "password": "supersecretpassword", "project": "project1"}' https://myurl.com/api/token/ I would like to be able to add project1 to the access token. Is there a way to add extra information in that manner? -
Spotify API 403 Forbidden Error When Adding Tracks to Playlist Despite Correct Token and Scopes
I'm experiencing a 403 Forbidden error when trying to add a track to a Spotify playlist using the Spotify Web API. Despite having a correctly configured token and permissions, I’m still facing this issue. Details: Spotify Client ID: 8273bf06015e4ba7a98ca3bbca70acaa Spotify Client Secret: a581f789e2f0442aa95bb33cfe0c7dcb Redirect URI: http://127.0.0.1:8000/callback Access Token Details: { "access_token": "my access token", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "my refresh token", "scope": "playlist-modify-private playlist-modify-public playlist-read-private playlist-read-collaborative", "expires_at": 1725396428 } Error Log: INFO 2024-09-03 20:16:02,097 cron Distributing 1 playlists to job scheduled at 2024-09-03 20:47:02.097874 for Order ID 28. INFO 2024-09-03 20:16:02,100 cron Adding track 0TT2Tzi8mEETCqYZ1ffiHh to playlist 4CeTjVTCZOFzTBdO8yaLvG ERROR 2024-09-03 20:16:02,557 cron Spotify API error: https://api.spotify.com/v1/playlists/4CeTjVTCZOFzTBdO8yaLvG/tracks: Check settings on developer.spotify.com/dashboard, the user may not be registered. ERROR 2024-09-03 20:16:02,558 cron Check if the user 31rizduwj674dch67g22bjqy7sue is correctly registered and has permissions to modify the playlist. What I’ve Tried 1- Verified Token Scopes: The token includes scopes playlist-modify-private and playlist-modify-public. 2- Checked Token Validity: The token is valid and has not expired. I also attempted to refresh it. 3- Confirmed Playlist Ownership: Ensured that the playlist is either owned by or shared with the user whose token is being used. 4- Re-authenticated: Re-authenticated and re-authorized the application to confirm there … -
ImproperlyConfigured: TaggableManager is not supported by modeltranslation
model.py from taggit.managers import TaggableManager class Blog(models.Model): tags = TaggableManager() fields.py if empty_value not in ("", "both", None, NONE): raise ImproperlyConfigured("%s is not a valid empty_value." % empty_value) field = cast(fields.Field, model._meta.get_field(field_name)) cls_name = field.class.name if not (isinstance(field, SUPPORTED_FIELDS) or cls_name in mt_settings.CUSTOM_FIELDS): raise ImproperlyConfigured("%s is not supported by modeltranslation." % cls_name) translation_class = field_factory(field.class) return translation_class(translated_field=field, language=lang, empty_value=empty_value) Can you help me buy such an error after the blog page tag loading process is completed? -
drf-spectacular not recognizing file upload type
I have a Django endpoint that takes a file upload My annotations look like this @extend_schema( request=UploadObservationalSerializer, responses={ 200: GenericResponseSerializer, 400: OpenApiResponse( response=ErrorResponseSerializer, description="Validation error or parsing error" ), 500: ErrorResponseSerializer }, description="Allow user to upload observational data" ) Here is my serializer: class UploadObservationalSerializer(BaseSerializer): calibration_run_id = serializers.IntegerField(required=True) observational_user_file_path = serializers.CharField(required=True) observational_file = serializers.FileField(required=True) def validate_observational_file(self, value): request = self.context.get('request') files = request.FILES.getlist('observational_file') if len(files) != 1: raise serializers.ValidationError("Only one observational file should be uploaded.") return value But in the Swagger, drf-spectacular lists observational_file as a String, not a File Field { "calibration_run_id": 0, "observational_user_file_path": "string", "observational_file": "string" } Why is drf-spectacular not recognizing the file field? -
How can I call delay task in zappa django
In celery I can call task with <func_name>.delay() How can I do it in zappa? I have task: @task() def task_name(): pass