Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django what is the logic behind creating in-app users the same way as admin users?
I was looking into how to create in-app users in Django by leveraging their auth system, and I founds this part of their docs: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model Personally, I do not like this approach because of three reasons: an in-app user will still have an empty permissions field. This is a bit scary, what if I misconfigure something? That could enable access to an in-app user to the admin panel. while both in-app user and admin panel users are similar in some aspects, they belong in two different worlds. To me, it would make more sense to have the auth system more flexible, and be able to use it with any kind of model, keeping the admin users separate from in-app users. having a separate model just to add more fields is an unnecessary overhead. But then, I am sure there are also some good reasons for this approach or maybe I am wrong and this is not the actual recommended approach. Any views on this? -
Why is my blacklisted token still allowing me to access an API in Django Rest Framework with Simple JWT?
In logout I blacklisted a token. But i can access a api using that blacklisted token. I used django restframework simple jwt and blacklist app for blacklisted token. In settings.py i have my jwt settings like this: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=1), 'USER_ID_CLAIM': 'id', 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'TOKEN_BACKEND': 'rest_framework_simplejwt.token_blacklist.backends.BlacklistBackend', 'BLACKLIST_TOKEN_CHECKS': [ 'rest_framework_simplejwt.token_blacklist.check_blacklisted_token', ], } In my views.py I am sharing two apis logout and hello api: from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework_simplejwt.tokens import RefreshToken class LogoutAPIView(APIView): def post(self, request): # Retrieve the user's refresh token from the request or any other means refresh_token = request.data.get('refresh') if refresh_token: try: print(refresh_token) token = RefreshToken(refresh_token) token.blacklist() # Blacklist the refresh token return Response({'detail': 'Successfully logged out.'}, status=status.HTTP_200_OK) except Exception as e: return Response({'detail': 'Invalid refresh token.'}, status=status.HTTP_400_BAD_REQUEST) else: return Response({'detail': 'Refresh token not provided.'}, status=status.HTTP_400_BAD_REQUEST) class HelloView(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request): user = self.request.user return Response(f"Hello, {user.username}!") When ever i hit the hello api with a token which is blacklisted and stored in DB, the api stills sends me the content. -
django can you filter for different value for each object in one query
how to filter for different value for each object and is there is a better way to validate that amount of sales items wont be bigger than purchases items here is what I think is wrong in SaleItemListSerializer I am making a for loop and for each item I get its medicine and expiry date then finding sum by making 2 subquery and a query so if I have 15 item there will be 15 query on the database the total response time is in average about 0.8 s in sqlite but in mysql it grows to 1.5 ( still i want to add retrived items and disposed items in the supquery so it will grow bigger ) so is there is a way to annotate all medicine that are in items each with its expiry date ( which is stored in sale items and purchase items ) in one database query ? I think I am making alot of mistakes I am still new to django any help will be appreciated class SaleAddSerializer(serializers.ModelSerializer): items = serializers.ListField(child=serializers.DictField(),write_only=True,min_length=1) class Meta: model = Sale fields = ['doctor_name','coustomer_name','items'] def validate_items(self,items): seen_items = {} for item in items: if set(item.keys()) != {'medicine', 'quantity', 'price', … -
How to check if a field can be left blank in Django templates?
I have simple ModelForm. Some of those fields can be left blank. In the template I'd like to let the user know which fields are required (not to be left blank) and which are not required (can be left blank). How to do that? This did not work: {% for field in form.visible_fields %} {% if field.blank %} * {% endif %} {% endfor %} -
Django Google Authentication - Login page unformatted
I have a web page built using Django and I just followed a tutorial (https://www.section.io/engineering-education/django-google-oauth/) to add Google Authentication for user registration. The functionality works fine, I added a button that users can click and go to the Google Sign-in Page. However, this page is completely unformatted, and doesn't look like what's in the tutorial (the Google choose your account page that we've probably all seen). I can't for the life of me figure out why my site isn't serving the same formatted page. I have 2 urls.py files, one in my main app page, and one in a users folder. users/urls.py looks like this: from django.contrib import admin from django.urls import path, include from users import views as user_views from django.contrib.auth.views import LogoutView urlpatterns = [ path('register/', user_views.register, name='register'), path('login/', user_views.login_user, name='user-login'), path('accounts/', include('allauth.urls')), path('logout', LogoutView.as_view()), ] In my settings.py file, I've added SOCIALACCOUNT_PROVIDERS , SITE_ID and LOGIN_REDIRECT_URL . What else could I be missing that would affect the format of this page? -
Page not found | Can't serve media files with Django
That's the bit of code that causes the problem: <video width="320" height="240" controls> <source src="{{ movie_path }}" type="video/mp4"> </video> The error message: Using the URLconf defined in fergana_api.urls, Django tried these URL patterns, in this order: admin/ api/schema/ [name='api-schema'] api/docs/ [name='api-docs'] api/ [name='all-runs'] tests/<slug:test_session_id> [name='single-run'] tests/<slug:test_session_id>/<slug:test_name> [name='single-test'] ^files/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, vol/web/media/36/movies/movie.mt4, didn’t match any of these. I'm trying to serve a mp4 file from a volume that's outside the project. I thought I could render the page by providing the absolute path to the file, since it's how I'd do it if I tried to open that page as an html file in browser. But this just doesn't seem to work out though I see that 'The current path' looks exactly as it should look. Not sure it's required in this case, but it's my urls.py for the app urlpatterns = [ path('', views.AllRunsView.as_view(), name='all-runs'), path('tests/<slug:test_session_id>', views.SingleRunView.as_view(), name='single-run'), path('tests/<slug:test_session_id>/<slug:test_name>', views.SingleTestView.as_view(), name='single-test'), ] views.py class SingleTestView(View): def get(self, request, test_session_id, test_name): run = Runner.objects.get(id=test_session_id) movies_dir_path = to_file(run.artifacts_dir_path, 'movies') movie_path = to_file(movies_dir_path, test_name.replace('-', '_') + '.mp4') context = { 'movie_path': movie_path } return render(request, "presenter/single_test.html", context) settings.py # under what url to serve static files in prod STATIC_URL = '/static/' … -
Removing Queryset <>tags from being displayed with my query
I am trying to display a query to a template and I am getting the correct data output but it is being displayed with Queryset<>tags, I believe the reason for this is using .all within my template to make the query but I am unable to figure out how I would display the information with out using .all models.py class SectionMeetingDate(models.Model): section_date = models.DateField() # time stamps when a cost center is created or updated updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.section_date) class SectionMeeting(models.Model): user = models.CharField(max_length=200) section_meeting_date = models.ManyToManyField(SectionMeetingDate, related_name='section_meeting_date') # time stamps when a cost center is created or updated updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) class CostCenterID(models.Model): name = models.CharField(max_length=200) dept_leader = models.CharField(max_length=200, null=True, blank=True) section_leader = models.ManyToManyField(SectionMeeting, related_name='section_leader') department_meeting = models.ManyToManyField(DepartmentMeeting, related_name='section_leader') # time stamps when a cost center is created or updated updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name views.py def cost_center_id(request, pk): # provides the name of the section leaders for each cost center ID names = CostCenterID.objects.get(id=pk) context = { 'names':names, } return render(request, 'DeptSummary/cost_center_id.html', context) cost_center_id.html {% for section_leaders in names.section_leader.all %} <h5> Section Leader -- <a href="{% url 'section_leader_date' section_leaders.id %}"> … -
Stop paypal access token from refreshing so frequently
Straight forward and simple question; What is the best way to stop PayPal access token from refreshing so frequently? I have tried to do curl command with extended 'expires_in': command. Doesn't work. Still refreshes after 24hr -
Why is my Django image not uploading in media/eventimg folder?
python class Events(models.Model): user_name = models.TextField() e_image = models.ImageField(upload_to='eventimg') e_poster = models.ImageField(upload_to='eventimg') e_end_date = models.DateTimeField() def __str__(self) -> str: return self.e_name def create_event(self, value): #value is send from view.py, below is its structure self.user_name = value['username'] self.e_image = value['image'] self.e_poster = value['poster'] self.e_start_date = value['startdate'] value dictionary structure which is been send as parameter value= { 'username': request.POST.get('userName'), 'image': request.POST.get('eventImage'), 'poster': request.POST.get('poster'), 'enddate': datetime.strptime(request.POST.get('endDate'), '%d-%m-%Y').strftime("%Y-%m-%d") } Image is not uploading in media/eventimg folder. When i upload it from admin panel it is working but when i try to do same from my webpage its not working. -
Changing Django admin template
I follow this video to change the Django admin templates, but it seems like the change doesn't go through. I am only changing "Welcome, username" to "Bello, username" to see if it works. Any suggestion? admin site file structure settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates/')], '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', ], }, }, ] -
ReactJS post request not sending values to Django backend
I have a React frontend component that is for Login/Account creation. The problem I'm facing is that when trying to register a new user I am getting a Bad Request error. After printing the request on the backend I see the request as <WSGIRequest: POST '/register/'> Here's my react function: const handleRegister = async (e) => { e.preventDefault(); try { const response = await axios.post("http://localhost:8000/register/", { method: "POST", mode: "cors", credentials: "include", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username, password }), }); const data = await response.json(); setMessage(data.success || data.error); } catch (error) { setMessage("An error occurred. Please try again."); } }; And here's my Django function: def register(request): print(request) if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if not username or not password: return JsonResponse({'error': 'Missing username or password'}, status=400) try: user = User.objects.create_user(username=username, password=password) login(request, user) return JsonResponse({'success': 'User registered and logged in'}) except Exception as e: return JsonResponse({'error': str(e)}, status=400) return JsonResponse({'error': 'Invalid request method'}, status=405) This is my request payload from the browser: { "method": "POST", "mode": "cors", "credentials": "include", "headers": { "Content-Type": "application/json" }, "body": "{\"username\":\"test\",\"password\":\"test\"}" } Response: {"error": "Missing username or password"} Not sure what I'm missing to make it so … -
Vue.js Build and Deploy to NGINX TypeError: Cannot use 'in' operator to search for 'path' in undefined
I am developing an E-Commerce. It is Vue.js with Django Rest Framework. It was working perfectly fine on my local machine. I had absolutely no errors. Now, once I did "npm run build" (I created the project by "vue create myproject") and uploaded it to my server, some pages stopped working, and on some pages there are tons of error codes. The APIs are working fine and can be accessed and the data served seen. The main problem is the Vue.js build that I get that doesn't work well. I hope you can help me. For example here I should have my products, but I get this: Here is what my broken homepage looks like (it should show the most sold products): Here is My router: import { createRouter, createWebHistory } from 'vue-router' import store from '../store' import axios from 'axios' import Home from '../views/Home.vue' import Products from '../views/shop/Products.vue' import Product from '../views/shop/Product.vue' import About from '../views/About.vue' import Corporate from '../views/Corporate.vue' import Contact from '../views/Contact.vue' import ContactThankYou from '../views/ContactThankYou.vue' import Login from '../views/auth/Login.vue' import SignUp from '../views/auth/SignUp.vue' import ResetPassword from '../views/auth/ResetPassword.vue' import ResetPasswordToken from '../views/auth/ResetPasswordToken.vue' import ResetPasswordMessage from '../views/auth/ResetPasswordMessage.vue' import ResetSetNewPassword from '../views/auth/ResetSetNewPassword.vue' import Account from '../views/auth/Account.vue' import ComplaintsBook from … -
Django models.FileField or serializer.FileField changes 2byte charactor file name
I am uploading 2byte charactor file name such as 木.pdf, When uploading, the file name is attached with randum alphabet,however this is OK. But, 2byte words are encoded automatically. Is it possible to suppress this? class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer def create(self, request, *args, **kwargs): // the name is kept here. print(request.FILES['myfile'])// <MultiValueDict: {'myfile': [<TemporaryUploadedFile: 木.pdf (application/pdf)>]}> if 'pdf' in request.FILES['myfile'].content_type: serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) print(serializer.data['myfile'])// it shows `http://localhost:8021/media/uploads/%E6%9C%A8_5R4Yjrw.pdf` file name is changed. my model and serializer is here below class Drawing(models.Model): myfile = models.FileField(upload_to='uploads/') detail = models.JSONField(default=dict) #detail = models.JSONField(default=default_value) user = models.ForeignKey(CustomUser,on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class DrawingSerializer(ModelSerializer): myfile = serializers.FileField() detail = serializers.JSONField() class Meta: model = m.Drawing fields = ('id','detail','myfile','user','created_at','updated_at') -
Is it possible to access both my Django project and Nginx Server on a single port forwarding?
My Django project is running on http://127.0.0.1:8000/ and Nginx Server is running on http://127.0.0.1:8080/ I want to access both on a single port forwarding (8081). Host Django and Nginx on the same port on the windows server. I've docker compose as: version: '3' services: web: build: . command: sh -c "echo 'Making migrations ' && python manage.py makemigrations && echo 'Migrating...' && python manage.py migrate && echo 'Running server...' && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" restart: always nginx-allure: image: nginx container_name: nginx-allure ports: - "8080:80" volumes: - type: bind source: ./allure-reports target: /usr/share/nginx/html read_only: true restart: always -
RabbitMQ creating idle queues having no consumers
Problems High Memory Usage Blocked Workers High Number of channels and Connections Blocked Connections Deployment Aws EKS I have a Django application and have long-running tasks implemented in celery with RabbitMQ as a Message broker and Result Backend. Over time it uses More memory and connections are getting blocked, when I inspected I found that celery workers are not able to get tasks from rabbitmq. I had logged in to the celery pod which was already running celery worker with the command: celery -A app_name worker -l info. I Logged in to pod and started workers with the same command and it started to consume tasks I understand connections are blocked if we have high memory usage. While debugging I checked I have a lot of random queues(1380 queues) without consumers ready to deliver messages and unpack messages, a large number of connections around 800, a large number of channels, and unused references(I had to clean up using rabbitmqctl force_gc then it started to work) but I am not able to replicate this scenario in my localhost. In my localhost when I start workers some temporary event queues are created and they destroy as soon as the worker stops, I … -
I can't figure out how my Django React Create Form returns, 'Unsupported Media Type: /api/auctions/'
My Django REST API uploads an auction correctly (including the required images) when I make a post request in Postman. However, my React auctioncreateform.js file does not successfully create an auction and instead returns the error below: 'Unsupported Media Type: /api/auctions/'. THE FORM WORKS AS INTENDED when I remove the uploaded_images values/attributes from the project. The post request through the form shows an error when I include the uploaded_images field. console.log(values); in my auctioncreateform.js returns these: bestdeals: false car_specification: [12] (1) category: 1 duration: 7 make: 1 model: 1 name: "jhjh" overview: "<p>gfgfg</p>" reserveprice: 0 start_time: "2023-05-27T10:53" starting_price: 0 type: "SUV" uploaded_images: Array (1) 0 File {path: "BM945737_dec96f.jpeg", name: "BM945737_dec96f.jpeg", lastModified: 1684687221000, webkitRelativePath: "", size: 83369, …} Array Prototype year: "2012" Below is my auctioncreateform.js import React, { useState, useEffect } from "react"; import clsx from "clsx" import { Formik, Form, Field, ErrorMessage } from "formik" import { useSnackbar } from "notistack" import Alert from 'react-bootstrap/Alert'; import Container from 'react-bootstrap/Container'; import axios from "axios"; import FilesDropzone from "../../../../components/Files-Dropzone"; import { postAuctionAxios } from '../../../../services/AuctionService' import { YupAuctionValidation } from "./schema/YupAuctionValidation" import { AuctionDefaultValue } from "./schema/AuctionDefaultValue" import { useNavigate } from "react-router" const AuctionCreateForm = props => { .... return … -
Django Forms: Display MultipleChoiceField select options below its label
In my views.py file, I have a form with the following field: test_type = forms.MultipleChoiceField(label="Test Type:", choices=ALL_TEST_TYPES_OPTIONS, widget=forms.SelectMultiple(attrs={'size': '15'})) I'm rendering it in my associated .html template file by using {{form.as_p}} inside of the following <form> tag: <form method="POST" action=""> {% csrf_token %} {{response.status_code}} - {{response.reason}} {{page_errors}} {{form.as_p}} It displays as such: My goal, which I'm seeking suggestions on how to achieve, is to simply put the select options below the label ("Test Type:"), rather than the current formatting of the select options being to the right of this label. Perhaps there's a command to perform this styling within its definition (in views.py as I inserted above) along the lines of what I did for setting its size attribute to be 15. Or, if there's a way I could break up its rendering in the HTML file to insert a <br> (line break) between the label and select options. -
Django admin add popup not working with many-to-many attribute on itself
Im trying to use in django admin a simple model like this: class Model1(models.Model): value = models.CharField(max_length=100) valuem2m = models.ManyToManyField("Model1", related_name="model1", blank=True) When try to add values in admin, if I try to open more than 1 popup, it didn't open another window, only redirect to the next form. first emergent window When I save this gives me this error. pup_response.js:13 Uncaught TypeError: opener.dismissAddRelatedObjectPopup is not a function at popup_response.js:13:16 window broken This is because the autogenerated id of the add button is the same of the child add button. (add_id_valuem2m). DevTools id's There is a way to make this work? -
Using Django TestCase, how do I create a test that sends a post request to my view, with data and files for a modelform
I have browsed SO, google, and have not been able to find a solution that works, or at least understand. I am currently using Django.test.TestCase to implement my tests. I am also using the built-in self.client to send POST requests. I have been successful with model and forms tests up to this point, but now that I am testing my views, I am not able to upload my SimpleUploadedFile image. I initially created the test in a similar manner to testing my form, with all data in one data dictionary submitted to my POST request. When I received errors, I assumed it was because I needed a second dictionary for 'files'. My research has led me to become more confused on this problem. I am not sure how to include request.FILES into my POST request or if self.client is simply not able to, and I need to use a third-party library. The view that I am sending the request to is as follows: # IMPORTS from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from crm_user.forms import * from crm_user.models import Address from django.forms.models import modelformset_factory # User Profile View @login_required def profile_view(request): """ This is a User Profile view""" … -
Playwright + Django: how to wait for events
In my tests, I have to wait for an event to trigger before continuing with test assertions, but I can't figure out how to make Playwright wait for that event. It seems like Playwright can't see the event. Simple example with a django page: clicking the button fires an event boop that changes the background color of the document. Template event.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Playwright Events</title> </head> <body><button>Click me</button> <script> const btn = document.querySelector("button"); btn.addEventListener("click", (e) => document.dispatchEvent(new Event("boop"))); document.addEventListener("boop", (e) => { document.body.style.backgroundColor = "darkcyan"; }); </script> </body> </html> URL conf: urlpatterns = [ path('', TemplateView.as_view(template_name="event.html")) ] The test: def test(page, live_server): page.goto(live_server.url) page.wait_for_timeout(500) btn = page.get_by_text('Click me') with page.expect_event("boop", timeout=1000): btn.click() page.wait_for_timeout(500) When running the test in headed mode, you can see the background color changing - meaning that the event boop was fired. But the test still fails because expect_event times out: playwright._impl._api_types.TimeoutError: Timeout 1000ms exceeded while waiting for event "boop" I must be doing something wrong, but I can't figure out what. Found this similar post, but it is not about playwright-python with django. -
How to choose template in DetailView based on a field of the model shown?
I have a model with a choice field: type = models.CharField(choices=TYPE_CHOICES, max_length=1, default=UNSET, db_index=True) Depending on the type I'd like to show a different template in the class based DetailView: class AlbumDetailView(DetailView): [...] Currently I have set the template by setting: template_name = 'bilddatenbank/album_detail.html' But then it's not possible to access the value of the model field. Where can I can set the template while having access to the model? Thank you. -
Error when calling Procedure from Django: No procedure matches the given name and argument types
I want to call a stored procedure installed in our PostgreSQL database via our Django backend. According to this stack question in order to call a procedure from Django we have to type it in a file named: test.py, placed in our migrations folder, like so: from django.db import migrations SQL = """ CREATE OR REPLACE PROCEDURE get_input_file() AS $$ CREATE TABLE TEMP(RowData VARCHAR(4000)); $$ LANGUAGE SQL; """ class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [migrations.RunSQL(SQL)] NOTES: python test.py resulted in nothing. python manage.py migrate api resulted in Operations to perform: Apply all migrations: api Running migrations: No migrations to apply. Then according to this guide we have added in our backend views.py the following code: # apply stored procedure import psycopg2 import os conn = psycopg2.connect( host=os.getenv('TDB_HOST'), database=os.getenv('TDB_NAME'), user=os.getenv('TDB_USER'), password=os.getenv('TDB_PASSWORD') ) cur = conn.cursor() cur.execute("CALL get_input_file();") conn.commit() We have expected this test to successfully call the procedure. We get: procedure get_input_file() does not exist LINE 1: CALL get_input_file(); ^ HINT: No procedure matches the given name and argument types. You might need to add explicit type casts. -
Django on HTTPS with react.js
I have this website deployed and it has an ssl certificate so it uses https. Now I want to link my Django backend to it so the website works as it supposed to. The react.js frontend and the Django backend are both hosted on a single AWS Lightsail instance. Now when I make a request to my django backend (I use an IP address) for example 1.2.3.4:8000/add It complains about that I'm using HTTPS and it only accepts HTTP. Now do I have to get a certificate for the Ip address or what is the best way/place to host my Django backend. All help is greatly appreciated! -
Django serve views asynchronously
Django 3.2.8 (a relatively old version) @csrf_exempt def xhrView(request, ms, status=200): sleep(ms / 1000) response = HttpResponse( f'{status} DUMMYXHRRESPONSE IN {ms}ms' ) response['Access-Control-Allow-Origin'] = '*' response.status_code = status return response I am hosting an api server for generative data testing with django. I have views for example serving purposes like: fetch or xhr js test generate fake json based on api query generate random long text but due to the python lang nature GIL, django is not capable of serving views asynchronously, which for example, if userA is visitng xhr/10000, any other user won't be able to even access the server in that duration. in those api views I don't need to access database, is there a way to serve the view above asynchronously? p.s. I have channels installed and is using websocket somewhere else for social messaging, the proj is set to asgi. I have tried consumers.py import asyncio from channels.db import database_sync_to_async from channels.generic.http import AsyncHttpConsumer from django.http import HttpResponse class XhrConsumer(AsyncHttpConsumer): @database_sync_to_async def sleep_ms(self, ms): return asyncio.sleep(ms / 1000) async def handle(self, body): ms = int(self.scope['url_route']['kwargs'].get('ms', 0)) await self.sleep_ms(ms) response = HttpResponse(f'{self.get_status()} DUMMYXHRRESPONSE IN {ms}ms') response['Access-Control-Allow-Origin'] = '*' await self.send_response(response) def get_status(self): return getattr(self, 'status', 200) # … -
Unable to do db index from python django
I tried to indexing my db from python django model class. But while doing migrate it throw error like this. psycopg2.errors.ReadOnlySqlTransaction: cannot execute CREATE EXTENSION in a read-only transaction Please help to resolve this issue. Is it because of any access problem. My db is in azure. I am able to read and write data to the db.