Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible in Django to use threaded=True (like in Flask) to e to handle each request in a new thread?
On Flask you can use threaded=True to handle each request in a new thread. For example: if __name__=="__main__": app.run(host="0.0.0.0", port=8000, threaded=True) With Django can i use something like threaded=True (or simil) to handle each request in a new thread? (without using async). Or is it more complicated in Django? -
Reverse for 'task_complete' with arguments '('',)' not found. 1 pattern(s) tried: ['tasks/(?P<task_id>[0-9]+)/complete\\Z']
estoy haciendo una todo app con Django y estoy queriendo hacer el update/delete de las tareas pero me salta el error del titulo, dejo las partes del código que, entiendo, son de interés: El HTML completa la tarea: <form action="{% url 'task_complete' task.id %}" method="POST"> {% csrf_token %} <button> Complete </button> </form> La lista de patterns: urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), path('singup/', views.singup, name="singup"), path('tasks/', views.tasks, name="tasks"), path('tasks/create/', views.create_task, name="create_task"), path('tasks/<int:task_id>/', views.task_detail, name="task_detail"), path('tasks/<int:task_id>/complete/', views.task_complete, name="task_complete"), path('logout/', views.singout, name="logout"), path('singin/', views.singin, name="singin"), ] La función que debería completarlas: def task_complete(request, task_id): task = get_object_or_404(Task, pk=task_id, user=request.user) if request.method == "POST": task.date_completed = timezone.now() task.save() return redirect('tasks') Esperaba que complete la tarea y deje de aparecer en tareas, pero tira el error Reverse for 'task_complete' with arguments '('',)' not found. 1 pattern(s) tried: ['tasks/(?P<task_id>[0-9]+)/complete\Z'] -
how to set log level for a specific url path in django?
my view is below @api_view(['GET']) def get_test(request): return HttpResponse('Ok', status.HTTP_200_OK) and my path in urls.py in urlpatterns is as below. path('api/test', views.get_test), This path is called a lot as part of the liveness probe in kubernetes and i want the log level just for this url to be set to CRITICAL so that it would not be logged or ideally i want to disable django logging altogether for this particular url and right now it is set to DEBUG by default. How do i go about changing the log level or disable the log? -
Error during template rendering in DjangoCMS plugin from {% translate 'Clear' %} [closed]
I’m trying to create a custom CMS Plugin and when i click to create the plugin this error happens: Error during template rendering from {% translate 'Clear' %} How can i solve this? In the past it was working. I don’t what happens. Thank you! I tryed to access the template "/usr/local/lib/python3.8/site-packages/filer/templates/admin/filer/widgets/admin_file.html" but i couldn't because it was build by docker. -
Power BI Embedded for customers - Creating embeded URL
I'm embedding a Power BI report on a "Embed for customer" manner and authenticating via service account. I have managed to get the embed token for a single report and a single workspace using Microsoft guides. The issue comes when making a POST request to https://api.powerbi.com/v1.0/myorg/groups/{workspace_id}/reports/{report_id}. I get a 403 error. Also, note that I am using Django and the final purpose is to process everything on the backend and just send a URL to the front end to put inside an iframe. This is my Django View: from django.shortcuts import render from django.views.generic import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin from django.http import JsonResponse from django.views import View from django.shortcuts import get_object_or_404 from .models import Dashboard, ReportConfig, EmbedConfig, EmbedTokenRequestBody from .serializer import DashboardSerializer from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from powerbi.aadservice import AadService import requests import json class DashboardView(viewsets.ModelViewSet): serializer_class = DashboardSerializer permission_classes = [IsAuthenticated] def get_queryset(self): # Retrieve the user's groups user = self.request.user user_groups = user.groups.all() # Filter the dashboards based on group membership queryset = Dashboard.objects.filter(group__in=user_groups) return queryset class PbiEmbedService(View): def get(self, request, workspace_id, report_id, additional_dataset_id=None): '''Get embed params for a report and a workspace''' report_url = f'https://api.powerbi.com/v1.0/myorg/groups/{workspace_id}/reports/{report_id}' api_response = requests.get(report_url, headers=self.get_request_header()) if api_response.status_code != … -
Django-MPTT using Parent and Child in same form
My goal is straightforward: I want to enable the selection of a parent category first and then choose its corresponding child categories. Unfortunately, I am encountering difficulties in implementing this functionality. My code is <form> <div class="mb-3"> <label for="main-category" class="form-label">Ana Kategori</label> <select class="form-select" id="main-category" name="main_category"> <option value="">Seçin</option> {% recursetree categories %} <option value="{{ node.id }}">{{ node.name }}</option> <div class="mb-3"> <label for="sub-category" class="form-label"></label> {% if not node.is_leaf_node %} <select class="form-select" id="children" name="children"> <option value="{{ node.id }}">{{ children }}</option> {% endif %} {% endrecursetree %} </select> </div> </div> <button type="submit" class="btn btn-primary">Gönder</button> </form> current result: -
Django - How to display search term on results page?
I’ve made a successful form and it’s working accordingly displaying the search results when a user makes a form submission. However, I’m stuck with one new addition to this search functionality. How do I get to display the search term with my current code? I’m trying to display the current search term in search_results.html but can’t get the term to display work. The only thing that appears is a blank space. I'm guessing I'm doing something wrong in views.py but don't know what exactly. Any help is gladly appreciated. Thanks! search_results.html <h1>Results for "search term here {{ title_contains_query }}”</h1> base.html (Where the search bar is located) <div class="search-container"> <form method="get" action="{% url 'search_results' %}"> <div class="input-group"> <input type="text" name="q" class="form-control gs-search-bar" placeholder="Search GameStation Games..." value=""> <span class="search-clear">x</span> <button type="submit" class="btn btn-primary search-button"> <span class="input-group-addon"> <i class="zmdi zmdi-search"></i> </span> </button> </div> </form> </div> views.py def is_valid_queryparam(param): return param != '' and param is not None def BootstrapFilterView(request): user_profile = User_Info.objects.all() user_profile_games_filter = Game_Info.objects.all() title_contains_query = request.GET.get('q') if is_valid_queryparam(title_contains_query): user_profile_games_filter = user_profile_games_filter.filter(game_title__icontains=title_contains_query) if request.user.is_authenticated: user_profile = User_Info.objects.filter(user=request.user) context = { 'user_profile': user_profile, 'user_profile_games_filter': user_profile_games_filter } else: context = { 'user_profile': user_profile, 'user_profile_games_filter': user_profile_games_filter } return render(request, "search_results.html", context) -
Django SQL Dealing
I'm working in a Django app and want to query one of my models to perform data dealing. I tried to perform from django.db import connections cursor = connections['default'].cursor() cursor.execute("select * from Collections") print(cursor.fetchall()) Got the following message: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Could not understand the problem since I am already querying models in my views with QuerySet. Any solutions? -
How to make transactions based on the frequency of transaction in Django
I'm new to Django, but I'm working on a project that allows users to create transactions. I would like to be able to create transactions that are recurring, based on a frequency. For example, a user could create a recurring transaction that is paid out every month. I'm not sure how to best implement this functionality. I've been looking at the django-scheduler library, but I'm not sure if that's the best way to go. Does anyone have any ideas on how to implement this functionality? Here is the transaction model that I'm using: class Type(models.TextChoices): """Class for transaction types.""" DEPOSIT = 'Deposit' PAYMENT = 'Payment' class Frequency(models.TextChoices): """Class for tansactin frequency""" ONETIME = 'One-time' DAILY = 'Daily' EVERY_WEEK = 'Every week' EVERY_TWO_WEEKS = 'Every two weeks' EVERY_THREE_WEEKS = 'Every three weeks' EVERY_MONTH = 'Every month' EVERY_TWO_MONTHS = 'Every two months' EVERY_QUARTER = 'Every quarter' EVERY_SIX_MONTHS = 'Every six months' EVERY_YEAR = 'Every year' EVERY_TWO_YEARS = 'Every two years' class Transaction(models.Model): """Transaction model.""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) transaction_type = models.CharField( max_length=30, choices=Type.choices, default=Type.PAYMENT, ) transaction_date = models.DateField() frequency = models.CharField( max_length=30, choices=Frequency.choices, default=Frequency.ONETIME, ) category = models.ForeignKey( Category, on_delete=models.CASCADE, null=True, blank=True, related_name='transactions', ) subcategory = models.ForeignKey( SubCategory, on_delete=models.CASCADE, null=True, … -
I get a 403 forbidden in my django project after submiting a form. I know there's a problem with CSRF token
I think the problem is in part due to the fact im not using the HTML template tag since, I'm creating a project using the JS generating the HTML from there. For addressing this in the HTML i added this script(before the js script I use): <script> var csrfToken = '{{ csrf_token }}'; </script> Im using the following script after the form code to send the information to my django project: const apiSendDataUser = (event) => { event.preventDefault(); const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value; const formData = new FormData (event.target); fetch('https://127.0.0.1:8000/myProject/post_user',{ method: 'POST', body: formData, headers: { 'X-CSRFToken': csrfToken } }) .then(response => { if (response.ok) { return response.json(); } else { throw new Error('Error: ' + response.status); } }) .then(data => { // Handle the response data console.log(data); }) .catch(error => { // Handle any errors console.error(error); }); }; And finally, the post_user function on the views.py is: @require_POST def post_user(request): try: email = request.POST['email'] if not User.objects.filter(email).exists() : username = request.POST['username'] password = request.POST['password'] User.objects.create_user(username=username, password=password, email=email) return JsonResponse( { "success":True, "message": "Usuario añadido." } ) except Exception as e: return JsonResponse({ "success": False, "message": e.args[0] }, status=404) I think is all, I dont know how to handle things with … -
django, the form is always wrong
I have a django application and I am writing two-factor authentication by email for it (a code should be sent to the mail). But the problem arises at the stage of checking the current email and password. as I understand it, the if form.is_valid() check does not work and constantly returns a form error. Please enter a correct %(username)s and password. Note that both fields may be case-sensitive. and This account is inactive. Although I am sure that I am entering the correct user data and there is is_active : True in the database table. My user model is redefined like this: class User(AbstractUser): email = models.EmailField(_("email_address"), unique=True) class RoleChoise(models.TextChoices): standard = "ST", "standart" admin = "AD", "admin" worker = "WK", "worker" inactive = "IA", "banned" role = models.CharField(choices=RoleChoise.choices, default=RoleChoise.standard, max_length=2) #another my fields my custom authorization function looks like this: class LoginOrSendCodeView(FormView): template_name = 'accounts/login.html' form_class = UserLoginForm success_url = reverse_lazy('login') def post(self, request, *args, **kwargs): if "OTP_code" in request.POST: ... #my other form handler, it works else: form = UserLoginForm(request.POST) if form.is_valid(): email = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, email=email, password=password) if user: if user.role != "IA": if user.two_factor_authentication: otp_model_object = OtpModel(user=user) otp_model_object.save() otp_model_object.send_otp_in_mail() return render(request, … -
KeyError: 'receiver' in self.scope[]
I am trying to retrieve data through self.scope[] in Django channels but I keep getting KeyError. How can I get the receiver part through self.receiver_username without the error? See the code details below: consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): self.receiver_username = self.scope['url_route']['kwargs']['receiver'] self.accept() routing.py websocket_urlpatterns = [ re_path(r'ws/socket-server/(?P<receiver>\w+)/$', consumers.ChatConsumer.as_asgi()), ] chat.html <div id="chat-messages"></div> <form id="form"> <input type="text" name="message" placeholder="Type a message..."> <input type="text" name="receiver" value="test"> <button id="send-button">Send</button> </form> <div id="messages"></div> <script> var receiver = 'test'; let url = `ws://${window.location.host}/ws/socket-server/` + receiver + '/' const chatSocket = new WebSocket(url) chatSocket.onmessage = function(e){ let data = JSON.parse(e.data) if(data.type === 'chat'){ let messages = document.getElementById('messages') messages.insertAdjacentHTML('beforeend', `<div> <p>${data.message}</p> </div>`) } } let form = document.getElementById('form') form.addEventListener('submit', (e)=> { e.preventDefault() let message = e.target.message.value chatSocket.send(JSON.stringify({ 'message': message })) form.reset() }) </script> When I try to retrieve the var receiver through self.receiver_username, I got the following error: KeyError: 'receiver' WebSocket DISCONNECT /ws/socket-server/test/ [127.0.0.1:51206] -
How to check if user is logged in using class based custom middleware?
I want to redirect not logged in users to login page every request they do. I have a custom class based middleware. I found on stackoverflow a solution to the problem using function based middleware. When I try to use this function inside my class, it doesn't work. But if I remove class and leave the function, it works fine. How can I fix this problem? # class based class CustomMidd: def __init__ (self, get_response): self.get_response = get_response def __call__(self, request): self.check_user(request) self.process_request(request) response = self.get_response(request) return response # def process_request(self, request): # allowed_ips = ['127.0.0.1'] # my ip # ip = request.META.get('REMOTE_ADDR') # if ip not in allowed_ips: # raise Http404 # return None def check_user(self,request): if request.user.is_authenticated or request.path == '/login/': response = self.get_response(request) return response return redirect('/login/') # function based def require_login(get_response): def middleware(request): if request.user.is_authenticated or request.path == '/login/': response = get_response(request) return response return redirect('/login/') return middleware It should also raise 404 error if ip is not allowed. So if I leave only function, it works, but I can't check ip now. When I try to enter main page, it returns an error Field 'id' expected a number but got.... This is because at the … -
Django form.is_valid() doesnt let anything go through. (False)
The program doesnt have any typos. when i try to write to the database via forms and press submit, the request will come back, but wont be inserted into database. # views.py from django.shortcuts import render from django.http import HttpResponse from .models import Book from .forms import BookForm # Create your views here. def homepage_welcome(request): return render(request, 'homepage.html') def addbook(request): if request.method == "POST": form = BookForm(request.POST) if form.is_valid(): form.save() return render(request, 'bookadded.html') return render(request, 'addbook.html') else: return render(request, 'addbook.html') def borrowbook(request): books = Book.objects.all() return render(request, 'borrowbook.html', {'booklist': books}) def book(request, pk): book = Book.objects.get(id=pk) context = {'book':book} return render(request, 'book.html', context) def bookadded(request): return render(request, 'bookadded.html') # forms.py from django.forms import ModelForm from .models import Book class BookForm(ModelForm): class Meta: model = Book fields = '__all__' # urls.py from django.urls import path from . import views urlpatterns = [ path('', views.homepage_welcome), path('addbook/', views.addbook, name='addbook'), path('borrowbook/', views.borrowbook), path('book/<str:pk>/', views.book, name = 'book'), path('bookadded/', views.bookadded), ] # models.py from django.db import models from django.utils import timezone # Create your models here. class Book(models.Model): booktitle = models.CharField(max_length=100) content = models.TextField() date_created = models.DateTimeField(default=timezone.now) I tried running the code without the if form.is_valid(): line, but that resoulted in "ValueError at /homepage/addbook/". then … -
Has superset functionality changed?
I've been using Django and superset in docker containers. I had these two lines of codes <div class="container"> <a target="_blank" href="http://localhost:8088/login?username={{ username }}&redirect=/superset/dashboard/services/?standalone=0&expand_filters=0">Explore Dataset</a> </div> <div> <iframe src="http://localhost:8088/login?username={{ username }}&redirect=/superset/dashboard/services/?standalone=&show_filters=1" style="position:absolute;top:220px;bottom:0px;width:100%;height:100%"></iframe> </div> Up until last week they have both worked. The first one to function as a link to the actual superset page and the iframe to show a specific dashboard on the page. I rebuilt my containers last week and now my iframe doesn't work. It shows 'localhost refused to connect.' The other link, however, does work still. Is anyone aware of a change in superset (or Django) and a possible fix or workaround to get this working again? -
django docker, how to copy local db data to the docker db?
I have dockerized a existing django app and an existing postgres database.the tables are created in the docker container. But the tables are empty . There is no data in it. if I connect to the docker container. And I do a \d+ | Schema | Name | Type | Owner | Persistence | Size | Description | --------+------------------------------------------+----------+---------------+-------------+------------+------------- | public | hotelWelzijnAdmin_animal | table | hotelwelzijn | permanent | 8192 bytes | | public | hotelWelzijnAdmin_animal_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | hotelWelzijnAdmin_category | table | hotelwelzijn | permanent | 8192 bytes | | public | hotelWelzijnAdmin_category_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | accounts_account | table | hotelwelzijn | permanent | 0 bytes | | public | accounts_account_groups | table | hotelwelzijn | permanent | 0 bytes | | public | accounts_account_groups_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | accounts_account_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | accounts_account_user_permissions | table | hotelwelzijn | permanent | 0 bytes | | public | accounts_account_user_permissions_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | … -
Can I use Prisma as the ORM inside of Django instead of Django's ORM?
I'd like to use Django + Django Rest Framework as my backend for a bunch of reasons (maturity, great tooling, security, etc.). I'm curious about using Prisma as the ORM layer instead of Django's ORM. Is there anything technically infeasible with this setup, or are there any major gotchas that may not be obvious that would make this a terrible idea? -
Make endpoint that returns a list of strings using Django Rest Framework
I have this Artist model: class Artist(models.Model): name = models.CharField(max_length=100) #songs = models.ManyToManyField('Song', related_name='artists') def __str__(self): return self.name class Meta: ordering = ('name',) I want to make a api endpoint that returns all the Artists row names as a list of string like for example: ["50 Cent", "Eminem", "Snoop Dogg", ...] . i have created this artists/names/ url in my urls.py: path('artists/names/', views.artist_names, name='artist_names'), I have tried two ways already: Using a python list: @api_view(['GET']) def artist_names(request): artists = Artist.objects.values_list('name', flat=True) artist_names_list = list(artists) return Response(artist_names_list) Using ListSerializer in my serializers.py: class ArtistNameSerializer(serializers.Serializer): name = serializers.ListSerializer(child=serializers.CharField()) and in my views.py i created the artist_names method: @api_view(['GET']) def artist_names(request): artists = Artist.objects.values_list('name', flat=True) serializer = ArtistNameSerializer(artists, many=True) return Response(serializer.data) From both of them when i go to the endpoint i get: GET /api/artists/names/ HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Can someone help? What am i doing wrong? -
Chart.Js - Chart-geo map is too small
I'm using the module Chart-Geo to make a choropleth map using Chart.Js It actually displays, but for some reason it's too small. I'm not trying to make a zoom option (using scroll) but just make it proper for visualization. I couldn't find a solution since Chart-Geo documentation doesn't enter in zoom topics. Seems like it's rendering the entire world size, but as it lacks data from other countries, it's just rendering Brazil. Observations: I'm using the framework Django. I'm using datamaps's data to get topoJson. Here is my code: home.html {% extends "base.html" %} {% block body %} {% load static %} <link rel="stylesheet" href="{% static 'css/home/home.css' %}"> <body> <div class="banner2Div"> <p>Cadastro por região</p> <canvas id="chart4" width="400" height="400"></canvas> </div> </body> <script src="{% static 'javascript/chart.umd.js' %}"></script> <script src="{% static 'javascript/index.umd.min.js' %}"></script> <script src="{% static 'javascript/d3.js' %}"></script> <script src="{% static 'javascript/bra.topo.json' %}"></script> <script type="module" src="{% static 'javascript/home.js' %}"></script> {% endblock%} Javascript const chart4 = document.getElementById('chart4') import brJSON from './bra.topo.json' assert {type: 'json'} const canvas_width = chart4.width const canvas_height = chart4.height const trlte_shift = [canvas_width / 71, canvas_width / 28.8]; const states = ChartGeo.topojson.feature(brJSON, brJSON.objects.bra).features; const chart = new Chart(chart4, { type: 'choropleth', data: { labels: states.map(d => d.properties.name), datasets: [{ label: 'States', … -
I'm using Django and Postgres on Docker, but I can't connect to the database after reinitialising
IMPORTANT NOTE: Django can't RECONNECT to the database. It works, then I try reinitialising it, and it stops working due to what's described below. I can get it to work if I reboot my PC, though. I'm running Django and PostgreSQL with Docker Compose (one container for Django and the other for PostgreSQL) I was using the container perfectly with no problems. After typing sudo docker compose down -vand sudo docker compose up -d, Firefox won't connect, and will show the message: The connection was reset So I run sudo docker compose logs -f to check the logs and Django says it can't connect to the Postgres database with the following messages: [...]port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? -
Can't write in input field, I'm using django and generating HTML from JS
I'll show you both my HTML and my JS code. Its simple by now, but this problem might be a challenge to all my project since I have several things that will work like this form. Apologies console.log message is in spanish, but it runs all the script. The problem is when i reach to the form itself i cant write anything, well you can write if you hold de click. Havent used any CSS, rather than the style thing on z i. const fillSection = (option = "user-registration", e ) => { console.log("you are filling section"); console.log(e); const content = document.querySelector('#user-registration') switch (option) { case "user-registration": content.innerHTML = `<form id="user-registration-form" method="post" style="z-index: 1000 !important;"> <div class="input-texts"> <div class="form-field"> <label for="name-user">Nombre</label> <input id="name-user" type="text" name="username" placeholder="Enter your name"> </div> <div class="form-field"> <label for="password-user">Password</label> <input id="password-user" type="text" name="password" placeholder="Enter your password"> </div> <div class="form-field"> <label for="email-user">Email</label> <input id="email-user" type="text" name="email" placeholder="Enter your email"> </div> </div> <button id="submit-button" class="form-btn" type="submit">Register</button> </form>`; const sendDataForm = document.getElementById("submit-button"); console.log("seleccionado el submit"); sendDataForm.addEventListener('submit', (e) => {apiSendDataUser(e)}); break; } }; const apiSendDataUser = (event) => { event.preventDefault(); const formData = new FormData (event.target); fetch('https://127.0.0.1:8000/videoHub/post_user',{ method: 'POST', data: formData }) .then(response => response.json()); } ; const registerSectionButton = … -
TemplateSyntaxError, Could not parse the remainder:
template.html {% with category2Choices=form.category2.field.choices.queryset.values_list("value", "display_name", "parent_id")|list %} <script> var category2Choices = JSON.parse('{{ category2Choices|json_script:"category2Choices" }}'); </script> {% endwith %} I am getting this issue: TemplateSyntaxError at /pages/add_product/ Could not parse the remainder: '("value",' from 'form.category2.field.choices.queryset.values_list("value",' I want to initially populate the main categories in a select field. When the user selects a main category, I want to dynamically fetch and display the subcategories related to that main category. To achieve this, I am using a small JavaScript code. Can you help me? -
How to maintain AnonymousUser session with Django test client
I have a Django TestCase where I would like to test an AnonymousUser visiting the same page twice. I would like to test that an action is only taken on the first visit, which is achieved by storing some data in the session upon the first visit. I can't use TestCase.client, because it uses a new AnonymousUser for each request and they have a new session. from django.test import TestCase class MyTestCase(TestCase): def test_my_test(self): self.client.get(url) response = self.client.get(url) self.assertTrue(...) -
Nginx authenticate iframe
I am running a django app on a server and i am running grafana on a different server with nginx as a reverse proxy (grafana and nginx are on the same server). I can manage to redirect an incoming URL and authenticate it via my backend, but I still get redirected to the grafana login screen, even when my django app sends a 200 response My setup: I am having a grafana server running under https with a nginx proxy. The nginx-setup server { server_name grafana.myserver.com; location / { proxy_set_header Host $host; proxy_pass http://localhost:3000/; proxy_set_header X-Real-IP $remote_addr; } location ~ ^/iframe(.*)$ { auth_request /iframe-auth; set $iframe_url http://localhost:3000$1$is_args$args; proxy_pass $iframe_url; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Authorization $http_authorization; } location = /iframe-auth { internal; proxy_pass https://blub.de/auth/check/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_set_header X-Original-URI $request_uri; } } In the above I am using the nginx auth module to redirect the incoming URL from the iframe the my django backend server. Here I do the authentication which works fine. I tested this by printing out the URL and I am authenticating the user and I am returning a 200 response if authenticated. Ok cool. I expected … -
CORES header issue in react django application
we are using django with react and in the settings.py file we have set the "CORS_ORIGIN_ALLOW_ALL" to True. we have also installed the coresheader app. but when the frontend is going to request for an api from 'http://localhost:3000/' but we still get the CORS policy error => Access to XMLHttpRequest at 'https://backend.com/api/v1/Category' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response. here is the settings.py file configurations: INSTALLED_APPS = [ ..., 'corsheaders', ] MIDDLEWARE = [ ...., 'corsheaders.middleware.CorsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'frontEnd/build'), os.path.join(BASE_DIR, 'templates'), ], 'DIRS': [os.path.join(BASE_DIR, 'templates'), # os.path.join(BASE_DIR, 'venv/lib/site-packages/django/contrib/admin/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', ], 'libraries': { 'staticfiles': 'django.templatetags.static', }, }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontEnd/build/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' CKEDITOR_UPLOAD_PATH = 'ck/' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full' }, } CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True and blew is how the frontend makes the api call requests using axios: import axios from 'axios' import { readCookie } from 'utils/readCookie' const isProduction = process.env.NODE_ENV === 'production' const csrfToken = readCookie('csrftoken') …