Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why to use the extra slash (/) at the end of the Django urls?
I'm trying to create a REST API using Django. I'm currently implementing the urls.py file. In a lot of different examples, I saw that they add / at the end of the url. For example: urlpatterns = [ path('login/', obtain_auth_token, name='api_token_auth'), ] I'm trying to figure way. Surely for login POST request which returns a token (given username and password), you want to access <domain>/api/login and not <domain>/api/login/. Currently I solved it with: urlpatterns = [ re_path(r'login$', obtain_auth_token, name='api_token_auth'), ] Or: urlpatterns = [ path('login', obtain_auth_token, name='api_token_auth'), ] But what is the convention? Why a lot of different examples add the extra / at the end? When do you want to add it? -
Django Multi-table inheritance - get parent object
How can I get the parent object from the child object in Multi-table inheritance? class Property(Model): .... class Meta: abstract = False #!!! class Flat(Property): .... flat = Flat.objects.first() flat.property >>> AttributeError: 'Flat' object has no attribute 'property There is a flat.property_ptr_id which I guess I could use but I'm curious if there is a more elegant/built-in way to do that. Btw. I know I can access all the fields from the child object. I'm working on methods like create_child, convert_child_type. -
How to create a pagination for a dataframe?
I want to create a pagination system for my dataframe. I always create pagination with my queries but It doesn't work in dataframe. I cannot display on my template. This is my views.py def get_context_data(self, **kwargs): ... df = pd.DataFrame(list(Case.objects.all().values(...))) query = df.assign(cnt=1).groupby([...)['cnt'].sum().reset_index() paginator = Paginator(query, 10) page_number = self.request.GET.get('page') if page_number == None: page_number = 1 page_obj = paginator.page(int(page_number)) print(page_obj) ----> <Page 1 of 33> context['query'] = query return context And this is my template <table class="table table-bordered" > <tbody> {% for index, row in query.iterrows %} <tr> {% for cell in row %} <td> {{cell}} </td> {% endfor %} </tr> {% endfor %} </table> Table shows nothing. How can I solve that? -
Django. How to create model instance in test db using objects fabric?
I want to make my unit tests setUp function clear from repeating tons of model creation lines like 1) create user 2) now create employee with fk to this user and etc. In order to do that I've made a simple factory of dummy objects but I might've done some mistakes or just misunderstood something. Here's a piece of factory (dummy_data is just a bunch of dicts): from abc import ABC from users.models import User from employees.models import Employee from .dummy_data import( user_data, employee_data, ) class DummyObjectFactory(ABC): """Fabric representing dummy test objects""" def get_dummy_object(self): """Return dummy object""" class DummyUser(DummyObjectFactory): def get_dummy_object(self) -> User: return User.objects.create_user(**user_data) class DummyEmployee(DummyObjectFactory): def get_dummy_object(self) -> Employee: user = DummyUser().get_dummy_object() return Employee.objects.create(**employee_data, user=user) Then I make a dot notaion dictionary of all kinds of fabrics for easy calling them buy dummy_factory.Name . My intetion was that I call fabric with the desired model name and it creates it's instance. The problem is: when I call it in some test's setUp method like so test_user = dummy_factory.User it creates object in actual database but I want it to be in test database. Yes, I've searched for the solution and found Factory boy and Faker libraries, but I … -
Colour code the rows in CSV file in my react-django project
I have an application running with react as the front end and Django at the backend. I want to make a download button where my panda data frame can be exported to Excel/CSV file with colour coded format in the downloaded CSV. Currently, i am using below code to download the file which is working but it gives me just the excel with data import { CSVLink } from "react-csv"; <CSVLink data={data} filename={"my-file.csv"} className="btn btn-primary" target="_blank" > Download me </CSVLink>; -
HTML: show different sized tables on the same page depending on the user's choice
Is it possible to implement two different sized tables where only one would be displayed on the page depending on the user's choice? E.g.: user chooses data table which has the following columns: country, price, date, so 3 columns would be displayed. Then the user chooses the users table with columns: name, email, so now 2 columns would be displayed. -
Django Make read only field
I write this code for making the readonly filed, but the problem after saving the page is it make all the columns read only . I want to make the if the filled has some value then that row will become readonly not all of them my code def get_readonly_fields(self, request, obj=None): if obj: return self.readonly_fields + ("name", "id") return self.readonly_fields -
How can I change the database time-out period in django?
I have django script which fetch the data from model. try: myuser = MyUser.objects.get(id=user_id) except Exception as e: print(e) # do next process Then, what I want to do is ,,, When database is stopped or not reached, I want to catch and do next process. However my program return the 502 immediately, because it reachs to the aws lambda's timeout. 2022-06-23 19:09:51 127.0.0.1 - - [23/Jun/2022 19:09:51] "POST /webhook HTTP/1.1" 502 - Function 'MyDjangoFunction' timed out after 300 seconds No response from invoke container for MyDjangoFunction Invalid lambda response received: Lambda response must be valid json So, my idea is set django - sql timeout shorter. Is there any good method?? -
Problem in panel of Django3.0 after migrations
why is the error appearing in django/admin? Migrations ok, I need to have 3 items in the table where I will have results. Thx for your help. class Robot(models.Model): """Robot model, speed and position simulation""" product = models.IntegerField(choices=CHOOSE) velocity = models.FloatField() positionX = models.FloatField() positionY = models.FloatField() angleTHETA = models.FloatField() class Meta:`enter code here` verbose_name = "Robot" verbose_name_plural = "Robots" def __str__(self): resum = self.get_product_display() return resum ProgrammingError at /admin/robot/robot/ column robot_robot.velocity does not exist LINE 1: ...LECT "robot_robot"."id", "robot_robot"."product", "robot_rob... -
id_username showing up in django form without reason
Im looking for some help with my custom user model. For whatever reason I cannot understand the field id_username pops up after clicking on the submit button. This field is missing from the form which I have cut down to {{ form.as_ p }} in the html urls.py path('login/', LoginView.as_view(template_name="registration/login.html"), name='login'), forms.py class LoginForm(forms.Form): email = forms.EmailField(label='Email', widget=forms.TextInput(attrs={'placeholder': 'Email'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) views.py class LoginView(FormView): form_class = LoginForm success_url = '/about/' template_name = 'registration/login.html' def form_valid(self, form): request = self.request next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(request, username=email, password=password) if user is not None: login(request, user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect("/about/") return super(LoginView, self).form_invalid(form) models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, help_text='Email Address' ) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser timestamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] # Email & Password are required by default. objects = UserManager() def get_full_name(self): # The user is identified by their email address return self.email ... etc ... @property def is_active(self): "Is the … -
Django - How to include form field logic in modelForm and not in a Createview, so that form can be unittested without also testing the view?
I have a Campaign Model, and a CampaignCreateForm which is a ModelForm. The Campaign model has a contact_list field of type JSONField. When a user is creating a campaign using the CampaignCreateFormthey upload a CSV file which is processed to create the JSON data for thecontact_list` field. What is the best way to approach this so that I can test the form separately from the view? I've built this using a CampaignCreateView which inherits from CreateView, and included the logic to parse the CSV file and create the JSON data in the views form_valid method, but this makes unit-testing the form (and any form field validation) impossible. I want to test the functions included in the forms clean method. With my current approach the view and form must be tested together, and that feels wrong. How can I create the form such that all the logic for the form (processing the CSV file to create the JSON data and discarding the uploaded file) is handled in the form only? My current CreateView and ModelForm are below: View: class CampaignCreateView(LoginRequiredMixin, CreateView): model = Campaign form_class = CampaignCreateForm # required if you want to use a custom model form, requires `model` also … -
Apps aren't loaded yet - Django, Gunicorn, Docker
I am trying to run my django project using gunicorn in docker. It worked perfectly while I used regular python manage.py runserver 0.0.0.0:8000 command. They I switched to using gunicorn command: command: > sh -c "export DJANGO_SETTINGS_MODULE='clubhouse.settings' && gunicorn clubhouse.wsgi" And now I have this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. docker-compose.yml version: '3.8' services: postgres: image: postgres ports: - '5432:5432' volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=clubhouse - POSTGRES_DB=clubhouse - POSTGRES_PASSWORD=secret redis: image: redis restart: always ports: - '6379:6379' command: redis-server --save 20 1 --loglevel warning --requirepass eYVX7EwVmmxKPCDmwMtyKVge8oLd2t81 volumes: - redis:/data api: build: context: . dockerfile: Dockerfile command: > sh -c "export DJANGO_SETTINGS_MODULE='clubhouse.settings' && gunicorn clubhouse.wsgi" volumes: - .:/code ports: - '8000:8000' env_file: - ./.env depends_on: - postgres - redis volumes: postgres_data: redis: full log: Starting clubhousebackend_redis_1 ... done Starting clubhousebackend_postgres_1 ... done Starting clubhousebackend_api_1 ... done Attaching to clubhousebackend_postgres_1, clubhousebackend_redis_1, clubhousebackend_api_1 postgres_1 | postgres_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization postgres_1 | postgres_1 | 2022-06-23 09:41:37.225 UTC [1] LOG: starting PostgreSQL 14.3 (Debian 14.3-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit postgres_1 | 2022-06-23 09:41:37.225 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2022-06-23 09:41:37.225 UTC [1] … -
Error response from daemon: failed to create shim: OCI runtime create failed: container_linux.go:380
I'm trying to run this command docker-compose run --rm app sh -c "flake8", but it fails with the following error: Error response from daemon: failed to create shim: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "/bin/bash": stat /bin/bash: no such file or directory: unknown Dockerfile content: FROM python:3.9-alpine3.13 LABEL maintainer="dsha256" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ &DEV = "true" ]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt ; \ fi && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="py/bin:&PATH" USER django-user docker-compose.yml content: version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > - sh -c "python manage.py runserver 0.0.0.0:8000" Any ideas to fix it? Thanks! -
How to find year-on-year growth from a query?
I have a dict type object in my Django app. I want to calculate Year-on-year growth(%) for every month. And the calculation for that is Percentage Growth in Cases Number compared to the previous year. And this is my data: <QuerySet [{'date_created__year': 2018, 'count_case': 1335}, {'date_created__year': 2019, 'count_case': 3469}, {'date_created__year': 2020, 'count_case': 3585}, {'date_created__year': 2021, 'count_case': 2589}, {'date_created__year': 2022, 'count_case': 144}]> I'm trying to create a template tag for that. @register.filter(name='get_yoy_query') def get_yoy_query(val,query): yoy = ? return yoy And in the template: {% for case in query_trend %} <td>{{case.count_case|get_yoy_query:query_trend}} %</td> {% endfor %} -
Django mptt Multiple references to class objects
I need to make a model for spices. Some spices may consist of others, or be basic. I need something like TreeForeignKey with multi-select option. I tried to use TreeManyToManyField, but I can't set null for base spices there. Here is my code: class Goods(MPTTModel): category = models.ForeignKey(Category, related_name='goods', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=150, db_index=True) parent = TreeManyToManyField( 'self', blank=True,) -
Mongo Aggregate - Match condition only on second collection but provide all documents from the first
Basically, I have 2 collections in my Mongo DB -> Books , Scores. Books { "BOOK_ID" : "100", "BOOK_NAME" : "Book 1", "BOOK_DESC" : "abcd", }, { "BOOK_ID" : "101", "BOOK_NAME" : "Book 2", "BOOK_DESC" : "efgh", }, { "BOOK_ID" : "102", "BOOK_NAME" : "Book 3", "BOOK_DESC" : "ijkl", } Scores { "BOOK_ID" : "100", "BOOK_CATEGORY" : "kids", "BOOK_SCORE" : "6", }, { "BOOK_ID" : "100", "BOOK_CATEGORY" : "Educational", "BOOK_SCORE" : "8", }, { "BOOK_ID" : "101", "BOOK_CATEGORY" : "Kids", "BOOK_SCORE" : "6", } { "BOOK_ID" : "101", "BOOK_CATEGORY" : "Fantasy", "BOOK_SCORE" : "7", } Expected output : Searching for all books with BOOKS_CATEGORY="Kids" and BOOKS_SCORE=6 { "BOOK_ID" : "100", "BOOK_NAME" : "Book 1", "BOOK_DESC" : "abcd", "BOOK_CATEGORY" : "Kids", "BOOK_SCORE" : 6 }, { "BOOK_ID" : "101", "BOOK_NAME" : "Book 2", "BOOK_DESC" : "efgh", "BOOK_CATEGORY" : "Kids", "BOOK_SCORE" : 6 }, { "BOOK_ID" : "102", "BOOK_NAME" : "Book 3", "BOOK_DESC" : "ijkl", } Notice that, for all the books to which scores are available, they are appended. If a Book does not have any score associated, it still comes in the result. What I have tried? I have tried using $lookup pipeline = [ { "$lookup": { "from": "Scores", … -
Huge discrepancy between access.log, Google Analytics and Mapbox Statistics
I have a website made in django and served using gunicorn in which a single Mapbox map is loaded on the home page using mapbox-gl.js. Users can then navigate the map and change styles at will. The map is initialized and loaded only once and only in the home page. The service is billed on a "map load" basis. The Mapbox pricing page says A map load occurs whenever a Map object is initialized, offering users unlimited interactivity with your web map. I would have expected to see a count, if not exactly identical, at least comparable between the data recorded by Mapbox billing, the accesses to the home page recorded by Google Analytics and the hits on the home page recorded on the server access.log. Instead, the Mapbox count is in average about 25 times higher than Analytics and the access.log, which have similar numbers. As an example, here are the numbers for yesterday: Analytics: home page was loaded 890 times access.log: 1261 requests for the home page Mapbox: 23331 map loads I am using URL restriction from the Mapbox control panel, but I guess the enforcement is not that strict, since they strongly suggest to also rotate the … -
Pass array data through AJAX and get in python file(views.py)
I want to pass array data in views.py file for that I use AJAX and passing data through AJAX. But there I am not able to get all data in views.py file, some of the data are missing. display.html var SelectedID = []; function getvalues() { $(':checkbox:checked').each(function (i) { SelectedID[i] = $(this).val(); $.ajax({ url: "{% url 'display' %}", type: "POST", dataType: "json", data:{ SelectedID : SelectedID[i], csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (data) { alert("Successfully sent the Data to Django"); }, error: function (xhr, errmsg, err) { alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText); } }); }); } views.py def display(request): is_ajax = request.headers.get('x-requested-with') == 'XMLHttpRequest' if is_ajax and request.method == "POST": SelectedID = request.POST.get('SelectedID') print(SelectedID) return render(request, 'display.html',{}) SelectedID[i] = $(this).val(); in this selectedID There are 10 records but in print of views.py there is only 6 records, other data are missing. -
How to filter queryset based on serializer field?
How to filter queryset based on query parameters and dynamically calculated serializer field? What i need: filter GET request output by payment_min and payment_max query parameters. In simple cases we can perform all filtering via annotation, but I have not found a way run custom function on each queryset element. My model class MortgageOffer(models.Model): bank_name = models.CharField( 'Наименование банка', max_length=200, unique=True, ) term_min = models.PositiveIntegerField( 'Срок ипотеки, ОТ', ) term_max = models.PositiveIntegerField( 'Срок ипотеки, ДО', ) rate_min = models.DecimalField( 'Ставка, ОТ', max_digits=4, decimal_places=2, ) rate_max = models.DecimalField( 'Ставка, ДО', max_digits=4, decimal_places=2, ) payment_min = models.PositiveIntegerField( 'Сумма кредита, ОТ', ) payment_max = models.PositiveIntegerField( 'Сумма кредита, ДО', ) class Meta: verbose_name = 'Ипотечное предложение' verbose_name_plural = 'Ипотечные предложения' My serializer class MortgageOfferFilteredSerializer(serializers.ModelSerializer): payment = serializers.SerializerMethodField() class Meta: model = MortgageOffer fields = '__all__' def get_payment(self, obj): return calculate_payment( int(self.context['request'].query_params['price']), int(self.context['request'].query_params['deposit']), int(self.context['request'].query_params['term']), float(obj.rate_max), ) My viewset class MortgageOfferViewSet(viewsets.ModelViewSet): http_method_names = ['post', 'patch', 'get', 'delete'] filter_backends = (DjangoFilterBackend,) filterset_class = MortgageOfferFilter def get_queryset(self): return MortgageOffer.objects.all() def get_serializer_class(self): if self.action in ('create', 'update', 'partial_update'): return MortgageOfferWriteSerializer elif self.action in ('retrieve', 'list'): if self.is_filter_request(): return MortgageOfferFilteredSerializer return MortgageOfferReadSerializer return super().get_serializer_class() def is_filter_request(self): return (self.request.query_params.get('price') and self.request.query_params.get('deposit') and self.request.query_params.get('term')) -
Building urls with django template system
So I need to build an url querying multiple objects. I tried to use the template system from django to build it with no success. I was wondering if there is any way of doing this in the template or if I should just write a view function. {% url 'service-ticket/new' as request %} {% with request|add:"?" as request %} {% endwith %} {% for entry in object.items.all %} {% with request|add:"spareparts="|add_string:entry.item.id|add:"&" as request %} {% endwith %} {% endfor %} <a class="btn-add float-right" href={{ request }} role="button"> THIS SHOW HAVE ALL </a> -
After refreshing angular application in browser: django response
I´m currently working on an application: Django backend and angular frontend. Everything works fine, but after refreshing one page in the browser I don´t get the angular response anymore. But what I get is a successful answer from my Django server (HTTPResponse: 200). My Django urls.py is as followed: from django.urls import path from quickstart import views # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('images/', views.ImageList.as_view()), path('images/<str:id>/', views.Image.as_view()), path('images/<str:id>/explanations', views.Explanation.as_view()) ] My app-routing.modules.ts: const routes: Routes = [ {path: 'home', component: MainComponent}, {path: 'images', component: ImageComponent, children: [ { path:':id', component: ImageDetailComponent } ]}, {path: '', redirectTo: '/home', pathMatch: 'full'}, ]; @NgModule({ imports: [RouterModule.forRoot( routes )], exports: [RouterModule] }) export class AppRoutingModule { } Thanks for helping! -
Django Model isn't migrating even after i saved and added app to installedApps
from django.db import models from django.contrib.auth import get_user_model user = get_user_model # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) text = models.TextField(max_length=100) author = models.ForeignKey( user, on_delete=models.CASCADE) created_date = models.DateTimeField() published_date = models.DateTimeField() PS C:\Users\hp\Desktop\djangomodels> cd I4G006918VEO PS C:\Users\hp\Desktop\djangomodels\I4G006918VEO> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. -
Django Rest Framework: After defining permissions I'm not able to access user details of logged in user
I want the admin user to access every user detail (GET, POST) and the non-admin user to get access to its own detail only but I'm getting error while implementing this. As I've shared my views.py, permissions.py, and models.py for the same. I'm using Postman for API testing and this is working fine for admin user but for an individual user, it's not working. views.py class UserListCreateAPIView(generics.ListCreateAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer class UserRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer permissions.py class IsStaffOrTargetUser(BasePermission): def has_permission(self, request, view): # allow user to list all users if logged in user is staff return request.user or request.user.is_staff def has_object_permission(self, request, view, obj): # allow logged in user to view own details, allows staff to view all records return request.user.is_staff or obj == request.user models.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','contact_number','gender','address','state','city','country','pincode','dob'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a … -
How do i increase the number of likes
How do i increase the number of likes in a answer models. I want when a user posted the answer, some user's in the application would be able to like it, like social media likes system, is anyone who can shows me how to increase the number of likes in my views and template ? I really don't know how to use count() function in the views and template, so this is my first time trying to add likes system in django application. class Answer(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, blank=False, null=False, on_delete=models.CASCADE) def __str__(self): return str(self.user) my like model: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Answer, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) my views: def viewQuestion(request, slug): question = get_object_or_404(Question, slug=slug) answers = Answer.objects.filter(post_id=question) context = {'question':question, 'answers':answers} return render(request, 'viewQuestion.html', context) my viewQuestion template: <div class="container"> {% for answer in answers %} <div class="row justify-content-center"> <div class="card my-2"> <div class="card-header"> Answer </div> <div class="card-body"> <h5 class="card-title">From: {{answer.user.username.upper}}</h5> <p class="card-text">{{answer.answer|safe}}</p> </div> </div> </div> {% endfor %} -
Django admin Resource Policy COEP ERR_BLOCKED_BY_RESPONSE
The static files of my Django admin site are on a S3 bucket (DigitalOcean Spaces actually) and in the Console I get a ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep 200 In the network panel all the static files are considered 3rd party and blocked for this reason (not same origin) The response to any one of these files contains a not set cross-origin-resource-policy error which says: To use this resource from a different origin, the server needs to specify a cross-origin resource policy in the response headers. What I tried : Following the error message, I tried to set a response header on the ressources, something like Cross-Origin-Resource-Policy: cross-origin. But in a DigitalOcean Spaces I cannot set headers other than Content-Type, Cache-Control, Content-Encoding, Content-Disposition and custom x-amz-meta- headers. I tried to extend the Django admin/base.html template, duplicate a few link tags and manually set a crossorigin attribute to them. This way the resources are queried twice, one query is blocked as before and the other one is working. The only difference in the headers is that the Origin is set. Is there a way to tell Django to add a crossorigin attribute to all link and script and img tags of the Django admin templates …