Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Populating db with initial data in Django
I need a way to populate db with initial data(cities) for my refs. So I've tried to do it through migrations(https://docs.djangoproject.com/en/4.0/topics/migrations/#data-migrations) Not sure it's a best way, since now I've made changes in this file after migration and can't apply it again, neither can't roll it back(since operation ...populate_cities... is not reversible) and apply again. So the questions are: is there a way to roll such migration back(may be manually)? may be there is a better way to populate db with such data -
Looping through <TD> and linking to whatever is in the loop - Django
I have a loop inside HTML that goes over every user and shows whats linked to it as shown in pic How do I make the HTML link to whatever is shown in the URL? using the following snippet : <td> <a href="{{ user.speciality }}">{{ user.speciality }} </td> will link me to http://127.0.0.1:8000/['http://127.0.0.1:8000/api/speciality/1/',%20'http://127.0.0.1:8000/api/speciality/2/'] -
I need simple django rest framework microservice project
There are 3 services in project. Services are: account category product -
Django restframework filtering with multiple query
I have viewset like this with django-restframework class MixViewSet(viewsets.ModelViewSet): serializer_class = MixSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filter_fields = ["id","user"] def list(self,request,*args,**kwargs): #filterset = FilterBook(request.query_params, queryset=Mix.objects.all()) queryset = self.filter_queryset(self.get_queryset()) #print(request.GET['access_token']) if ('at' in request.GET): try: user = AccessToken.objects.get(token=request.GET['at']).user except: print("access token invalid") return Response({'message':'invalid access token'}) print(user.id) queryset = queryset.filter(user=user) #http://localhost:8008/api/mixs/?access_token=128 serializer = self.get_serializer(queryset, many=True) custom_data = { 'items': serializer.data } custom_data.update({ 'meta':{"api":"Mix"} }) return Response(custom_data) def get_queryset(self): queryset = Mix.objects.all() ids = self.request.query_params.get('id') print(ids) if ids is not None: queryset = queryset.filter(id=ids) return queryset class MixSerializer(serializers.ModelSerializer): pub_date = serializers.DateTimeField(format="%m/%d/%Y,%I:%M:%S %p") class Meta: model = Mix fields = ('id','pub_date','detail','user') Now I want to get the items by multiple id such as https://example.com/mix/?id=100&id=112&id=143 however in this case only 143 works and it returns the one row. How can I make this work for multiple query?? -
How to Make use of Pagination in this API using Django
Here I am trying to create a getData API using Django Rest Framework in which i want to get data using Pagination, i had created this statically but it should be like (getting PAGE and number of ROWS on that page) in request and accordingly data get fetch from database and also show the number entries i got. please help me out to solve this, i have no idea about how pagination works logically just have basic understanding. class DeviceControlPolicyView(APIView): def get(self, request): if request.data.get('page', 'rows'): if request.data.get('page') == "1" and request.data.get('rows') == "1": print(request.data.get('rows')) print(request.data.get('page')) qry = DeviceControlPolicy.objects.all()[0:1] serializer = DeviceControlPolicySerializer(qry, many=True).data entries = 1 data = { 'details':serializer, 'entry':entries } return Response(data) elif request.data.get('page') == "1" and request.data.get('rows') == "2": print(request.data.get('rows')) print(request.data.get('page')) qry = DeviceControlPolicy.objects.all()[0:2] serializer = DeviceControlPolicySerializer(qry, many=True).data entries = 2 data = { 'details': serializer, 'entry': entries } return Response(data) -
Client sent an HTTP request to an HTTPS server Docker Django Nginx
I have recently started learning docker and I created a django app which I went ahead and dockerized. I am however experiencing an error I can't get past. The error message is Client sent an HTTP request to an HTTPS server. Here is my nginx config file server { listen 80; listen [::]:80; server_name 192.168.99.106; charset utf-8; location /static { alias /usr/src/app/static; } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } And here is my docker-compose.yml version: '3' services: web: restart: always build: ./web expose: - "8000" links: - postgres:postgres - redis:redis volumes: - web-django:/usr/src/app - web-static:/usr/src/app/static env_file: .env environment: DEBUG: 'true' command: sh -c "python manage.py makemigrations && python manage.py migrate && usr/local/bin/gunicorn inventory.wsgi:application -w 2 -b :8000" nginx: restart: always build: ./nginx/ ports: - "80:80" volumes: - web-static:/www/static - ./certbot/www:/var/www/certbot/:ro - ./certbot/conf/:/etc/nginx/ssl/:ro links: - web:web certbot: image: certbot/certbot:latest volumes: - ./certbot/www/:/var/www/certbot/:rw - ./certbot/conf/:/etc/letsencrypt/:rw command: certonly --webroot -w /var/www/certbot --force-renewal --email example@gmail.com -d 192.168.99.106 --agree-tos postgres: restart: always image: postgres:latest ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ environment: POSTGRES_DB: "db" POSTGRES_HOST_AUTH_METHOD: "trust" POSTGRES_PASSWORD: ${DB_PASS} redis: restart: always image: redis:latest ports: - "6379:6379" volumes: - redisdata:/data volumes: web-django: web-static: pgdata: redisdata: The docker … -
WebSocket connection to 'url' failed
I just deployed a django project that uses djagno channels in heroku.. when I try to create a websocket connection form http://localhost:3000/ to the url, I am getting connection to websocket failed Is this due to improper deployment or something else I am not able to understand can anyone help me.. This is how i am connecting to websocket useEffect(() => { Socket = new WebSocket(`${WEBSOCKET_URL}/room/${roomName}/${myUserName}/`); Socket.onmessage = ({ data }) => { let res = JSON.parse(data); if (!res.error && res["data-type"] === "begin-game") { const { gameId } = res; Socket.close(); navigate(`/game/${gameId}/`, { state: { gameId, data: res.data, myUserName }, }); } else if (!res.error) setUsersOnRoom({ ...res.data }); }; }, []); where WEBSOCKET_URL is export const WEBSOCKET_URL = "wss://ludo-thegameforlegends.herokuapp.com/ws"; The codes in my django project is in asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter,URLRouter from channels.auth import AuthMiddlewareStack from main.routing import websocket_urlpatterns as room_urlpatters from gameManager.routing import websocket_urlpatterns as gameManager_urlpatterns from channels.security.websocket import AllowedHostsOriginValidator os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ludo.settings') websocket_urlpatterns = room_urlpatters + gameManager_urlpatterns application = ProtocolTypeRouter({ 'http':get_asgi_application(), 'websocket':AllowedHostsOriginValidator(AuthMiddlewareStack(URLRouter(websocket_urlpatterns))), }) I am configuring channel layers like this CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [(os.environ.get('REDIS_URL'), 6379)], }, }, } routing is like this.. from django.urls import … -
why does css file is not working in django project
When i shutdown my PC and reopen my project every time i have to change the css file name to see the changes on the web i have tried many ways to fix this issues. *i have researched online but i did not get any answer on it * i have tried these ways to fix this error i have tried settings up STATIC_ROOT=''. i have tried setting up STATICFILES_DIRS=[]. please guide me to solve this error. -
Can We Have Two Views For The Same Page - Django
I am working on a simple project of creating a e-commerce for having a product and orders pages for customer and admin of website. Now I wanted the same product page for both customer and admin but admin should have more options like editing that product or who ordered the product whereas customers shouldn't be able to see this. Is it possible by creating a different views but passing two different values or can we use jinja tags for this ? NB : I am beginner so please forgive me if i missed a point or while explaining please use simpler terms. Thanks For Answers -
Diagnosing diseases in python
I want to create a system to diagnose diseases. This system has a test and asks some questions from user. New question apears base on the user's answer. Finally shows the result according to the user's answers. I want to design this system using django and react. I will be happy if you recommand me the way I should choose to create it. Thank you. -
Not able to install psycopg2 module when deploying Django to Elasticbeanstalk
I am having trouble adding the psycopg2 module to my elastic beanstalk setup, so that I can deploy my Django project. Some details: Platform: Amazon Linux 2/3.3.14 Python 3.8 running on 64bit Stack Trace from /var/log/web.stdout.log Jun 22 02:39:11 ip-172-31-20-172 web: return _bootstrap._gcd_import(name[level:], package, level) Jun 22 02:39:11 ip-172-31-20-172 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 29, in <module> Jun 22 02:39:11 ip-172-31-20-172 web: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) Jun 22 02:39:11 ip-172-31-20-172 web: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' Jun 22 02:39:11 ip-172-31-20-172 web: [2022-06-22 02:39:11 +0000] [3578] [INFO] Worker exiting (pid: 3578) Jun 22 02:39:11 ip-172-31-20-172 web: [2022-06-22 02:39:11 +0000] [3572] [INFO] Shutting down: Master Jun 22 02:39:11 ip-172-31-20-172 web: [2022-06-22 02:39:11 +0000] [3572] [INFO] Reason: Worker failed to boot. Jun 22 02:39:11 ip-172-31-20-172 web: [2022-06-22 02:39:11 +0000] [3586] [INFO] Starting gunicorn 20.1.0 Jun 22 02:39:11 ip-172-31-20-172 web: [2022-06-22 02:39:11 +0000] [3586] [INFO] Listening at: http://127.0.0.1:8000 (3586) Jun 22 02:39:11 ip-172-31-20-172 web: [2022-06-22 02:39:11 +0000] [3586] [INFO] Using worker: gthread Jun 22 02:39:11 ip-172-31-20-172 web: [2022-06-22 02:39:11 +0000] [3592] [INFO] Booting worker with pid: 3592 Jun 22 02:39:12 ip-172-31-20-172 web: [2022-06-22 02:39:12 +0000] [3592] [ERROR] Exception in worker process Jun 22 02:39:12 ip-172-31-20-172 web: Traceback … -
How to create tables in a different schema in django?
I'm using postgresql database in my django project. I have multiple apps in my projects. users/ UserProfile model myapp/ CustomModel model Now I need UserProfile table should be created in public schema And CustomModel table needs to be created in a separate schema called myapp How to implement this and Do I need to change anything in the queries or migration command in future after implementing this? -
How does Django handle importing of apps?
I would like to know how Django's imports work. For example, in this code: # in some_app/views.py from another_app.models import UserModel # another_app is another app of the same project there's an import statement that imports UserModel from models.py in another_app (another app of the same project). I was just wondering how Django handles this importing because usual Django project's directory structure looks like this: . ├── another_app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── manage.py ├── some_app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── some_project ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py some_app and another_app are separate directories. I want to know how the importing works because I want to find a workaround for one of my projects that have separate directories but requires each other's functions. -
Django CORS Missing Allow Origin Error even with corsheaders middleware
Hi I'm building a SPA with Django + Vue.js and struggling with CORS Missing Allow Origin error. It occurs when Vue.js frontend call some API and Django backend returns redirect to external URL. From Django backend, this API returns something as below. return redirect('https://api.external.service.com/sso/authorize?param1=xxx&param2=yyy>') And then Vue.js frontend tries to redirect to the URI but it fails. Since console tells "CORS Missing Allow Origin", I'm using corsheaders with the following configuration, but it doesn't solve the issue. What's wrong with what I'm doing?? settings.py DJANGO_DEBUG = True ALLOWED_HOSTS = ('localhost', 'api.external.service.com',) CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ('https://localhost:8000', 'https://0.0.0.0:8000', 'https://api.external.service.com',) ... INSTALLED_APPS = [ ... 'django_extensions', 'corsheaders', 'rest_framework', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] For debug, I tried the follows but it also failed with the same error... settings.py DJANGO_DEBUG = True ALLOWED_HOSTS = ('*',) CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ('https://localhost:8000', 'https://0.0.0.0:8000', 'https://api.external.service.com',) ... INSTALLED_APPS = [ ... 'django_extensions', 'corsheaders', 'rest_framework', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] Otherwise am I misunderstanding "CORS", and perhaps I should register my app domain to the external service to allow access from my app to it?? -
Django Signals: Creating instance of different models when one is created based on a boolean field on the sender model
I have three models ProductOrService, Product and Service. I have a BooleanField named is_product in the ProductOrService model which says that an item is a product if it is true and it is a service if it is false. I want to automatically create a Product instance if the is_product field is True or automatically create a Service instance if the is_product field is False. The code given below creates a Product instance when a ProductOrService instance is created with is_product set to True. But it does not create a Service instance when a new ProductOrService instance is created with is_product set to False. models.py: class ProductOrService(models.Model): web_id = models.CharField(max_length=50, unique=True, verbose_name=_("product web id"), help_text=_("format: required, unique")) slug = models.SlugField(max_length=255, null=False, blank=False, verbose_name=_("product/service url"), help_text=_("format: required, letters, numbers, underscore or hyphen")) name = models.CharField(max_length=250, null=False, blank=False, verbose_name=_("product/service name"), help_text=_("format: required, max_length=250")) seller = models.ForeignKey(User, related_name="product_or_service", on_delete=models.PROTECT) description = models.TextField(verbose_name=_("product description"), help_text=_("format: required")) category = TreeManyToManyField(Category) is_visible = models.BooleanField(default=True, verbose_name=_("product/service visibility"), help_text=_("format: true->product is visiible")) is_blocked = models.BooleanField(default=False, verbose_name=_("product/service blocked"), help_text=_("format: true->product is blocked")) created_at = models.DateTimeField(auto_now_add=True, editable=False, verbose_name=_("date product/service created"), help_text=_("format: Y-m-d H:M:S")) updated_at = models.DateTimeField(auto_now=True, verbose_name=_("date product/service last updated"), help_text=_("format: Y-m-d H:M:S")) is_product = models.BooleanField(default=True, verbose_name=_("Is this product?"), help_text=_("format: … -
AJAX-based refresh without data duplication
I am confused about AJAX requests. I am using the load() function to refresh specific elements on the page. Unwanted duplication does not occur when there is only one matched element on the page. {% for example in examples %} <div class="refresh" id="single{{ example.id }}"> <div class="container"> <p> Different content </p> </div> </div> {% endfor %} Assuming the above example, I would like to refresh the contents of a container with different contents in multiple elements on the page. In this case, if the 'examples' elements are four, there will be 8 after the refresh. I've tried everything I can find, but so far the data is duplicated. -
Django 4 seems to be caching my query. How can I turn it off?
Some context I have a model with 20+ attributes. This is for a property-listing site (like Airbnb). So there are things like size, bedrooms, city, state, etc. There needs to be an auto-complete functionality on the textboxes when I am editing these properties. So for example, State is a text field in my form. When I am adding a 2nd house to my website, the State textbox should suggest values from the previous houses that I have in my system. (Basically when I type C, it should show California if I have any houses with California already in the DB) UpdateView I am using an Update View to show my Property-Edit (House-Edit) page. I need to pass in all these auto-complete fields inside this Update View so that I can add them to my text boxes. The code looks like this: class PropertyUpdateView(LoginRequiredMixin, UpdateView): context_object_name = 'property' model = models.Property form_class = forms.PropertyForm template_name = 'desertland/admin/property_update.html' extra_context = get_autocomplete_fields() def get_success_url(self): messages.success(self.request, 'The property was updated successfully.') return reverse('property_update', kwargs={'pk': self.object.id}) The extra_content is where I am passing my autocomplete fields. The get_autocomplete_fields() method is like so: def get_autocomplete_fields(): ac_keys = ['state', 'city', 'county', 'zip_code', 'zoning', 'power', 'water_district', 'water', 'access', … -
127.0.0.1:8080/data/ping should return pong json response (something like {‘data’:‘pong’}
I am using Redis in my project for caching, now I need to return pong in the browser when i point to the /data/ping and also other Redis CLI operations if possible, I did some research and found something in js but I need to implement this in pure Django or DRF -
I am getting the error disallowed host with python anywhere
I am trying to deploy my blog to python anywhere but I keep getting this error DisallowedHost at /. The error log says this Invalid HTTP_HOST header: 'codewizblog.pythonanywhere.com'. You may need to add 'codewizblog.pythonanywhere.com' to ALLOWED_HOSTS. I do not know why it is asking me to add something I have already added to my sittings file. if anyone knows how to fix this any help would be appreciated. Also if anyone can give me tips on security for my site that would also be appriceated. setting.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['codewizblog.pythonanywhere.com',] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ '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 = 'blog.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 = 'blog.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } … -
Django - get message from websocket
I would like to be able to receive a message from the user POST /createEvent and immediately give it to all other users via websocket /wsEvens But it's not clear to me how to make interaction between these interfaces in Django I use Django + DRF -
Problems configuring site on PythonAnywhere
I am trying deploy a test web app on PythonAnywhere by pulling my code from my Github repo using a helper tool by PythonAnywhere. I used this command: $ pa_autoconfigure_django.py --python=3.8 https://github.com/<your-github-username>/repository.git Then after a prompt for my username and password ( had to use a token because it is required) and putting them in I got this error: remote: Write access to repository not granted. fatal: unable to access 'https://github.com/Username/Myrepo.git/': The requested URL returned error: 403 Traceback (most recent call last): File "/home/Username/.local/bin/pa_autoconfigure_django.py", line 49, in <module> main( File "/home/Username/.local/bin/pa_autoconfigure_django.py", line 31, in main project.download_repo(repo_url, nuke=nuke), File "/home/Username/.local/lib/python3.8/site-packages/pythonanywhere/django_project.py", line 20, in download_repo subprocess.check_call(['git', 'clone', repo, str(self.project_path)]) File "/usr/lib/python3.8/subprocess.py", line 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['git', 'clone', 'https://github.com/username/repo.git', '/home/username/username.pythonanywhere.com']' returned non-zero exit status 128 Can someone tell me what im doing wrong? -
How deep can "django-nested-admin" have nested inlines?
django-nested-admin shows the code example which has 3 levels "TableOfContentsAdmin", "TocSectionInline" and "TocArticleInline" as shown below: # An example admin.py for a Table of Contents app from django.contrib import admin import nested_admin from .models import TableOfContents, TocArticle, TocSection class TocArticleInline(nested_admin.NestedStackedInline): # 3rd Level model = TocArticle sortable_field_name = "position" class TocSectionInline(nested_admin.NestedStackedInline): # 2nd Level model = TocSection sortable_field_name = "position" inlines = [TocArticleInline] class TableOfContentsAdmin(nested_admin.NestedModelAdmin): # 1st Level inlines = [TocSectionInline] admin.site.register(TableOfContents, TableOfContentsAdmin) Now, how deep can django-nested-admin have nested inlines? Only 3 levels? -
I don't want drf ValidationError response string boolean
raise ValidationError(detail={"something": True}) Response: { "something": "True" } Looging for: { "something": true } -
The view main.views.home didn't return an HttpResponse object. It returned None instead
Okay so I looked through a few different slack posts on this ValueError, but it seemed most of them had to do with not returning render which it seems like I am doing that correct..? I am sure it has to do with my if statements, just not sure what exactly or how to set the code up correctly so I can check the form request to the browser. views.py: from http.client import responses from django.shortcuts import render from .forms import SearchUser from .search import search def home(request): if request.method == "POST": form = SearchUser(request.POST) if form.is_valid(): form.cleaned_data["name"] else: return render(request, "main/home.html", { 'form': SearchUser(), # Reference to form 'userid': search(request), # 'mmr':NA, }) search.py: import requests def search(request): data = requests.get( f"https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/{name}/NA1?api_key=RGAPI-d1224a2c-9130-45ff-8c05-0656d56d105f") return data.json()['puuid'] urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.home, name=""), #path("", views.search, name=""), ] home.html: {% extends 'main/base.html'%} {% block content %} <h2>Valorant Ranked Checker</h2> <form method="post" action=""> {% csrf_token %} {{form}} <button type="submit" name="search"> Get rank </button> </form> <p><strong>{{userid}} - {{mmr}}</strong></p> {% endblock %} -
Django & React implementation using Google OAuth2 does not work with csrftoken
I have implemented Django backend for Google OAuth2 signin/signup process for user authorization. The mechanism is triggered from React UI. The user can successfully signup using Django backend and I can see the associated users are created in Django Admin. However, when I try to use the same user information through React UI, "me" API call cannot access to the Django user that has signed in. But direct Django call through browser and curl command works fine. The following command works fine with backend call : curl -X GET --header "Cookie: csrftoken=M1kFFNataWZcbckfdrqUEiXuRRsSRwYKKCH4XvENUyWnLE9xnSMHe7DiaUcDBRU6; sessionid=p156z2d5gy9cwamojxvmxbopg84p99v6" http://localhost:8000/registration/me/ Below is Django settings for Cors and CSRF : CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] CORS_ALLOW_ALL_ORIGINS=True CORS_ALLOW_CREDENTIALS = False CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000' ] CSRF_COOKIE_NAME = "csrftoken" CSRF_COOKIE_HTTPONLY = False CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"] CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_AGE = None CSRF_COOKIE_DOMAIN = 'localhost' CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = True CSRF_USE_SESSIONS = True Below is rest framework settings : REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSIONS_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } The API call from Django for "me" : @api_view(['GET']) def current_user(request): from rest_framework.permissions import IsAuthenticated permission_classes = [IsAuthenticated] user = request.user if user.is_authenticated: return Response({ 'username' : user.username, …