Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
relation "account_account_groups" does not exist LINE 1: ... "auth_group"."name" FROM "auth_group" INNER JOIN "account_a
admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from account.models import Account class AccountAdmin(UserAdmin): list_display = ('email','username','date_joined', 'last_login','is_admin','is_staff') search_fields = ('email','username',) readonly_fields=('id', 'date_joined', 'last_login') filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Account, AccountAdmin) models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user def get_profile_image_filepath(self, filename): return 'profile_images/' + str(self.pk) + '/profile_image.png' def get_default_profile_image(): return "chatapp/default.png" class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="email",max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image) hide_email = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.username def get_profile_image_filename(self): return str(self.profile_image)[str(self.profile_image).index('profile_images/' + str(self.pk) + "/"):] # For checking permissions. to keep it simple all admin have ALL permissons … -
I can't get the field that contains the object from another model when I create a record
models.py: class A(models.Model): name = models.CharField(max_length=120) def save(self, args, **kwargs): super().save(args, **kwargs) print(self.a_name.all()) class A1(models.Model): description = models.CharField(max_length=120) name = models.ForeignKey(A, on_delete=models.CASCADE, related_name="a_name") class Tags(models.Model): name = model.CharField(max_length=120) a1 = models.ForeignKey(A1, on_delete=models.CASCADE, related_name="a1_tags") admin.py: class TagsI(nested_admin.NestedTabularInline): model = Tags extra = 1 class A1I(nested_admin.NestedTabularInline): inlines = [TagsI] model = A1 extra = 1 class AI(nested_admin.NestedTabularInline): inlines = [A1I] model = A extra = 1 I can't get the field that contains the object from another model when I create a record. I get an error self.a_name.all() A' object has no attribute 'a_name'. How do I get this related object when I save the record? -
Django MRO for permission subclasses
I am using Django 3.2 I have a model Foo, and I want users to be able to update/delete objects that they created. To that end, I have written a OwnerPermissionMixin class as follows: /path/to/permissions.py class OwnerPermissionMixin(PermissionRequiredMixin): owner_attribute = 'owner' def has_permission(self) -> bool: """ Require the the user has the relevant global permission and is the owner of this object. :return: Does the user have permission to perform this action? """ return self.request.user.is_superuser or ( super().has_permission() and self.request.user == getattr(self.get_object(), self.owner_attribute) ) /path/to/views.py class FooUpdateView(LoginRequiredMixin, OwnerPermissionMixin, UpdateView): model=Foo class FooDeleteView(LoginRequiredMixin, OwnerPermissionMixin, DeleteView): model=Foo My question is: am I inheriting the base classes in the right order? both Mixins have the same base class AccessMixin - and it seems to make sense (from a philosophical point of view), that LoginPermissions are enforced before Owner permission - but I want to make sure I'm not missing anything obvious. -
Taggit Django - Return View of Posts Based on User Post Tags)
I have recently been playing around Taggit. I have managed to filter my Posts model, based on different Tags by adding the following filter .filter(tags__name__in='categoryone'). Although, would anyone be able to provide me with guidance on how to filter my Posts based on the tags my user has already used within his or her previous posts? So for example, if my user has previously created a Post within the "categoryone" tag, all the posts he or she would see on their Post Feed would be tags relevant to "categoryone" but he or she wouldn't see any posts within "categorytwo" or "categorythree" unless he or she makes a post within either or both of those categories. I was hoping something such as .filter(tags=self.request.user) but this is throwing an Instance error. Any examples would be greatly appreciated! :-) Thanks! -
Django sending Html email template with javascript functions
I am trying to send an HTML Template over email in DJANGO site and for some reason javascript part isn't working . Email is sent sucessfully with an image only a function is not working in email browser. Here's the template code. <html> <script> function validate() { var x = document.forms["form"]["eid"].value; if (x == "E101") { document.getElementById('id1').style.display='block'; return false; } } </script> <body> <h2 style="color:red;">Hello </h2>,<br> <p >Please find the OTP for requested file.<p><span style="width" class="">File Name :{0} </span></p> <p ><span style="width" class="">OTP : {1} </span></p> <div id="id1" style="display:none;"><img src="cid:0" ></div> <form name="form" onsubmit="return validate()" method="post" required> Employee id: <input type="text" name="eid"> <input type="submit" value="Submit"> </form> <p> </body> </html> -
custom result per logged in user in Foreign Key dropdown django admin
I have a model Called Business and it has many BusinessAddress inside. When userA creates Business say - business_a and then when he creates the BusinessAddress business_address_a_1 He could be able to choose the business_a in the dropdown. But when userB creates his business_b and then when creating the BusinessAddress, dropdown form for foreign key Business in Django admin should not show business_a and business_b instead it should only show business_b and if more business created by the userB that too. My model sample is like this class Business(models.Model): title = models.CharField(max_length=200) def __str__(self): # Show title as the identifier return self.title class BusinessAddress(models.Model): business = models.ForeignKey(Business, on_delete=models.DO_NOTHING) address = models.CharField(max_length=200) def __str__(self): return self.business.title I earlier added the changes to only show the business and business address of the particular user using overriding the get_queryset . But Since Django is new to me I couldn't find a way to achieve this. Could someone guide me on this? -
Best Way to Override Bootstrap Colour Variables
I have a Django (Wagtail CMS) project and I am trying to create a functionality that will allow me to change the 8 Bootstrap theme colours, more about that here. In order to override those colours, I need to use Bootstrap via the SCSS source. I'm using django-compressor to compress the static files in HTML and django-libsass as a SASS compiler. This is in my settings file (settings/base.py) COMPRESS_OFFLINE = True LIBSASS_OUTPUT_STYLE = 'compressed' LIBSASS_SOURCEMAPS = True LIBSASS_PRECISION = 6 This is my HTML file (templates/base.html) {% compress css %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <style type="text/x-scss" media="screen"> $dark: #000000; </style> <link rel="stylesheet" type="text/x-scss" href="{% static 'scss/bootstrap/bootstrap.scss' %}"> {% endcompress %} I am trying to override the "dark" theme colour with #000, this hex will be replaced with a template tag. The above code doesn't seem to work. But, the code below works: {% compress css %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <style type="text/x-scss" media="screen"> $dark: #000000; @import "engine/static/scss/bootstrap/bootstrap.scss" </style> {% endcompress %} Now the second code snippet of my base.html file works perfectly, but having an @import seems to be very inefficient. I could create a custom SCSS file with my own colour overrides, but … -
docker-compose up gets stuck at .env doesn't exist
I want to insert environmental variables from an .env file into my containerized Django application, so I can use it to securely set Django's settings.py. However on $docker-compose up I receive part of an UserWarning which apparently originates in the django-environ package (and breaks my code): /usr/local/lib/python3.9/site-packages/environ/environ.py:628: UserWarning: /app/djangoDocker/.env doesn't exist - if you're not configuring your environment separately, create one. web | warnings.warn( The warning breaks at that point and (although all the container claim to be running) I can neither stop them from that console (zsh, Ctrl+C) nor can I access the website locally. What am I missing? Really appreciate any useful input. Dockerfile: (located in root) # pull official base image FROM python:3.9.5 # set environment variables, grab via os.environ ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 # set work directory WORKDIR /app # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # add entrypoint script COPY ./entrypoint.sh ./app # run entrypoint.sh ENTRYPOINT ["./entrypoint.sh"] # copy project COPY . /app docker-compose.yml (located in root; I've tried either using env_file or environment as in the comments) version: '3' services: web: build: . container_name: web command: gunicorn djangoDocker.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/app … -
Cannot completely terminate celery [windows 10]
I have a problem here that I believed to originate from an unkilled celery worker: nttracker\celery.py from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nttracker.settings') postgres_broker = 'sqla+postgresql://crimsonpython24:_16064Coding4Life@host/nttracker' app = Celery('nttracker', broker='amqp://', backend='rpc://', include=['nttracker.tasks']) app.autodiscover_tasks() app.conf.update( timezone = "Asia/Taipei", result_backend = 'django-db', broker_url = 'redis://127.0.0.1:6379', cache_backend = 'default', beat_schedule = { 'add-every-10-seconds': { 'task': 'nttracker.tasks.add', 'schedule': 10.0, 'args': (16, 16) }, } ) if __name__ == '__main__': app.start() nttracker\tasks.py from __future__ import absolute_import import django django.setup() from celery import Celery from celery.schedules import crontab app = Celery() @app.task def add(x, y): z = x + y print(z) output from celery -A nttracker.celery worker --pool=solo -------------- celery@LAPTOP-A0OM125L v5.0.5 (singularity) --- ***** ----- -- ******* ---- Windows-10-10.0.19041-SP0 2021-06-04 23:02:25 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: nttracker:0x1a520896400 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: - *** --- * --- .> concurrency: 12 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [2021-06-04 23:02:26,607: WARNING/MainProcess] c:\users\xxx\onedrive\desktop\github_new\nttracker\venv\lib\site-packages\celery\fixups\django.py:203: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn('''Using settings.DEBUG … -
matching query does not exist in database
whenever I try to get my list of items in query I am getting this error from django.db import models Create your models here. class ToDo(models.Model): name = models.CharField(max_length = 200) def __str__(self): return self.name class Item(models.Model): todolist = models.ForeignKey(ToDo, on_delete = models.CASCADE) text = models.CharField(max_length = 300) complete = models.BooleanField() def __str__(self, text = text): return self.text that line i am executing in my pycharm terminal In [3]: lt = ToDo.objects.get(id = 1) --------------------------------------------------------------------------- DoesNotExist Traceback (most recent call last) <ipython-input-3-23a0e6ec0ffa> in <module> ----> 1 lt = ToDo.objects.get(id = 1) ~\anaconda3\lib\site-packages\django\db\models\manager.py in manager_method(self, *args, **kwargs) 83 def create_method(name, method): 84 def manager_method(self, *args, **kwargs): ---> 85 return getattr(self.get_queryset(), name)(*args, **kwargs) 86 manager_method.__name__ = method.__name__ 87 manager_method.__doc__ = method.__doc__ ~\anaconda3\lib\site-packages\django\db\models\query.py in get(self, *args, **kwargs) 433 return clone._result_cache[0] 434 if not num: --> 435 raise self.model.DoesNotExist( 436 "%s matching query does not exist." % 437 self.model._meta.object_name DoesNotExist: ToDo matching query does not exist. -
social_auth_app_django pipeline: first time visitor issue
I'm trying to implement social auth with google-oauth2. I almost implemented it, but I'm confused about first-time social visitor scenario: Suppose the social user visited my site for the first time and attempted to authenticate with using Google. In this case he won't be logged in, but only registered on my website. In order to log in this user has to click on authentication with Google button the second time, and when he already registered on my system the logging in will be successful. Questions: Is it a standard routine for the first time visitors? Is it possible to log the social user on the first attempt? I'm using the following social auth pipeline: SOCIAL_AUTH_PIPELINE = ( # Get the information we can about the user and return it in a simple # format to create the user instance later. In some cases the details are # already part of the auth response from the provider, but sometimes this # could hit a provider API. 'social_core.pipeline.social_auth.social_details', # Get the social uid from whichever service we're authing thru. The uid is # the unique identifier of the given user in the provider. 'social_core.pipeline.social_auth.social_uid', # Verifies that the current auth process is … -
i didn't use django auth to login, but i want to use django sessions
I need help and I don't have so much time left, so basically I'm making an app for my end studies project, this app requires login, of course, and I didn't pass the Django auth which already provided by Django, but now instead of getting back and changing the code which I don't have much time to do so, I'll looking for sessions solution, I didn't how to implement it, can someone help me please, if you need more details just tell me, I'll provide you with everything. Thanks. -
Check if a user is in a group before posting. How to select all available groups in my function?
I am new in Django and my first project was buildidng a simple social clone. My site allows people to post something in different groups, but I want to check if a user is already in that group before posting. I think that the main problem I don't know how to select all the groups in order to verify my condition. models.py from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete=models.CASCADE) views.py from django.contrib.auth import get_user_model User = get_user_model() from django import template register = template.Library() @register.filter def has_group(user, group): return user.groups.filter(name=group).exists() ##### ..... #### class CreatePost(LoginRequiredMixin,SelectRelatedMixin,generic.CreateView): fields = ('message','group') model = models.Post def form_valid(self, form): if has_group(self.request.user, ""): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) else: messages.error(self.request, 'Join the group first') return HttpResponseRedirect(reverse('groups:all')) I was trying to resolve this, but I was unsuccessful. Thank you. -
Github actions django rest unit testing ValueError: Port could not be cast to integer value as 'None'
I have a Django and Django REST app, and when I run my unit testing locally, every runs and passes. However, when I create a GitHub Action to run my unit testing, some of my unit tests failure with the following message: File "/opt/hostedtoolcache/Python/3.9.5/x64/lib/python3.9/urllib/parse.py", line 178, in port raise ValueError(message) from None ValueError: Port could not be cast to integer value as 'None' Here is my Action: django-test-lint: runs-on: ubuntu-latest services: postgres: image: postgres:12.3-alpine env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: github_actions ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - name: Checkout uses: actions/checkout@v2 - name: Set up Python 3.9 uses: actions/setup-python@v1 with: python-version: 3.9 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: psycopg2 prerequisites run: sudo apt-get install libpq-dev - name: Run migrations run: python app/manage.py migrate - name: Run tests and lint with coverage run: | cd app coverage erase coverage run manage.py test && flake8 coverage report -m -
Django - Query values based on the result of an existing query
I have a query that matches some foreign key properties buy_book__entity and sell_book__entity to a parameter company_group. I need to further add onto this query to filter the results only on the results that match a predicate. Is this possible to do in one query? return (Q(buy_book__entity__company_groups__alias__iexact=company_group) & \ Q(sell_book__entity__company_groups__alias__iexact=company_group)) & \ # I only want to run the below query on objects which # the book entity types are internal (Q(buy_book__entity__primary_company_group__alias__iexact=Case( When(buy_book__entity__type=ENTITY.INTERNAL, then=Value(company_group)), default=Value(None))) | \ Q(sell_book__entity__primary_company_group__alias__iexact=Case( When(sell_book__entity__type=ENTITY.INTERNAL, then=Value(company_group)), default=Value(None)))) I tried the above query utilizing Case and When but this doesn't exactly work because it will give the value as None to the primary_company_group whereas I need it not to query by that at all, almost like an ignore. Since primary_company_group is a nullable foreign key this skews my results heavily. Just FYI, I don't want to filter all entity__type to internal. Just the ones that are internal, I need to run the further query on those. -
Pycharm not recognizing django models, appconfig, etc
I am using Pycharm 2021.1.1, It was all fine, suddenly when I try to write from django.apps import AppConfig It is showing unsolved reference AppConfig from django.db import models It is showing Unsloved reference models But I have installed all necessary modules, like Django, DjangoRestFramework, and the actual virtualenv is activated. -
How to serialize JSON Request data from serializer in Django?
I am trying to serialize a json data through serializers.Serializer { "data": { "phoneNumber": "1234567890", "countryCode": "+11", "otp": "73146", } } The sterilizer class I wrote for it and also I don't know why source is not working, I tried the JSON in the picture below but still it's saying the field is required -
Is there any added advantage of using djangorestframework over JsonResponse?
I am new to Django and API creation. I am trying to figure out if it is better to use djangorestframework or just use JsonResponse. I got the suggestion of djangorestframework from Digital Ocean's tutorial but also found out about JsonResponse, which seems simpler given that I don't have to install another package. Goal: I would like to be able to provide user information for both web and mobile applications. I see that there are some reasons provided on this post for djangorestframework, which I pasted below for posteriority. The common cases for using DRF are: 1)You're creating a public-facing external API for third-party developers to access the data in your site, and you want to output JSON they can use in their apps rather than HTML. 2)You're doing mobile development and you want your mobile app to make GET/PUT/POST requests to a Django backend, and then have your backend output data (usually as JSON) to the mobile app. Since you don't want to pass back HTML to the mobile app, you use DRF to effectively create a REST API that your mobile app can call. 3)You're creating a web app, but you don't want to use the Django templating … -
The Request parameter for views function in Django greys out
No matter what I try in vs code the request is always greyed out. I'm following the Django tutorial and I get a 404 when loading the server because the index function can't be called cause the parameter is greyed, This works perfectly fine in Pycharm, but not vs code. Any solutions? def index(request): return HttpResponse("Hello, world. You're at the polls index.") -
View_by_Course_list() missing 1 required positional argument: 'course_code_and_name'
I have used Django to develop a web app. When I tried to pass a string in the url, error occurs: View_by_Course_list() missing 1 required positional argument: 'course_code_and_name' view.py: @csrf_exempt def View_by_Course_list(request, course_code_and_name): if request.method == 'POST': ... url.py: path('View_by_Course_list/$',views.View_by_Course_list, name='View_by_Course_list'), HTML: <a href="{% url 'bms:View_by_Course_list' %}?course_code_and_name={{course_for_select}}" id=" {{course_for_select}}" onclick=""> {{course_for_select}}</a> I got the error: k return view_func(*args, **kwargs) TypeError: View_by_Course_list() missing 1 required positional argument: 'course_code_and_name' How should I correct it? -
ImproperlyConfigured - UserRegisterView is missing a QuerySet. Define UserRegisterView.model, UserRegisterView.queryset, or override
sorry to be a bother. I have just created a user login app for a blog site, but I keep getting this error whenever I try to go to the registration page: "UserRegisterView is missing a QuerySet. Define UserRegisterView.model, UserRegisterView.queryset, or override UserRegisterView.get_queryset()." Below is my view.py file from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy class UserRegisterView(generic.CreateView): form_Class = UserCreationForm template_name = 'registration/register.html' success_url = reverse_lazy('login') I'm not entirely sure where I need to go from here. Any help/explanation would be really helpful. -
Django project on Heroku processing long requests. Background Jobs and Queueing
I have a Django project on Heroku, The project has an endpoint that accepts the client's request and sends it to other external services, the approximate response of which is from five seconds to two minutes. As known, if the process takes longer than 30 seconds, the platform will return an error h12 request timeout (and in general, the answer to the request must be given as soon as possible). I studied Background Jobs and Queueing and realized that I would need such instruments as RQ and Celery. In general terms, I understand the concept of each individual topic, but I do not really understand how to apply this to the project and whether I correctly assembled a bunch of tools for my task. Also, I don't understand how I can save the response of external services and I will need to inform the initiator of the request to my server (client request) about the result. I would be grateful for any hints, suggestive answers, and helpful resources. Thank you -
I'm unable to get data from RESTful API using DRF and REACT
In the backend I am using permission_classes = [IsAuthenticated], I'm logged in running django server on port 8000 using rest framework interface and then I m trying to fetch data from port 3000 . So I want to know why there is error on port 8000 terminal Forbidden: /api/drive-links/ [04/Jun/2021 18:11:01] "GET /api/drive-links/ HTTP/1.1" 403 58 Django Rest Framework API HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "title": "Clip", "link": "https://drive.google.com/file/d/12345" } ] RESTdataSource.js contains import Axios from "axios"; // Config global defaults for axios/django Axios.defaults.xsrfHeaderName = "X-CSRFToken"; Axios.defaults.xsrfCookieName = "csrftoken"; export class RestDataSource { constructor(base_url) { this.BASE_URL = base_url; } GetData(callback) { this.SendRequest("get", this.BASE_URL, callback); } async SendRequest(method, url, callback) { callback( ( await Axios.request({ method: method, url: url, }) ).data ); } } And Isloated Table contains import React, { Component } from "react"; import { RestDataSource } from "./RESTdataSource"; class IsolatedTable extends Component { constructor(props) { super(props); this.state = { DriveLinks: [], }; this.dataSource = new RestDataSource( "http://localhost:8000/api/drive-links/" ); } render() { return ( <table className="table table-sm table-striped table-bordered"> <thead> <tr> <th colSpan="5" className="bg-info text-white text-center h4 p-2"> DriveLinks </th> </tr> <tr> <th>ID</th> <th>Name</th> <th>Drive Links</th> <th></th> </tr> </thead> … -
Creating custom Django encrypted field with Fernet
I'm trying to create a django custom encryption field using Fernet. The libraries I found for doing it automatically seems to be outdated/non compatible with Django>3.0 In this thread I found the following code: import base64 from django.db.models import CharField from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from core import settings class SecureString(CharField): salt = bytes(settings.SECURE_STRING_SALT, encoding="raw_unicode_escape") kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) key = base64.urlsafe_b64encode(kdf.derive(settings.SECRET_KEY.encode('utf-8'))) f = Fernet(key) def from_db_value(self, value, expression, connection): return str(self.f.decrypt(value), encoding="raw_unicode_escape") def get_prep_value(self, value): return self.f.encrypt(bytes(value, encoding="raw_unicode_escape")) It seems to work for the encoding part (if I check the database field with a manager program, content is show as a sort of chinese characters), but not for decoding. Everytime I save a record in Admin, this error is triggered (although saved in database): raise TypeError("{} must be bytes".format(name)) TypeError: token must be bytes Aren't supposed to be already as bytes in the database record, due to get_prep_value code? The same error happens when trying to list records in admin (accessing the reading function). How can I solve this? I am using SQL Server as database (in case it might be relevant). -
Access-control-allow-origin header not recognised in browser
We've aded some javascript code to a web-page which needs to POST information to our Django-backend for analysis. In the head of the site, we've added a line like this: <script src="https://somedomain.com/track/" type="text/javascript"></script> In turn it will fetch the complete code and do what it needs to. However, I'm running into an issue with Access-Control-Allow-Origin. I've added a custom middleware to the Django-project that looks like: class CorsMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) response["Access-Control-Allow-Origin"] = "*" return response I can try out the url and its headers via requests: import requests resp = request.get resp = requests.get('https://somedomain.com/track/') print(resp.headers['Access-Control-Allow-Origin']). # Prints "*" Those work - yay. But when I'm trying this out on the actual website, I keep getting the error [Error] Failed to load resource: Origin https://www.websitedomain.com is not allowed by Access-Control-Allow-Origin. What am I missing?