1

I am writing a django application where I have a model called Website which contains websites of people. I only allow people who have their websites in my database to use my Django REST API. I am using the django-cors-headers package to whitelist the domains of people: https://github.com/adamchainz/django-cors-headers.

CORS_ORIGIN_WHITELIST variable in settings.py allows me to white list domains as shown in https://github.com/adamchainz/django-cors-headers#cors_origin_whitelist

The problem is that I have to query my models to get the website domains, append them to a list and then put that list into CORS_ORIGIN_WHITELIST. But I can't do that in settings.py because models are loaded after the app starts and settings.py is the one that starts the app.

Does anyone know a way around that? Any suggestions will be appreciated. Thanks in advance.

dirkgroten
  • 20,112
  • 2
  • 29
  • 42
sshussain270
  • 1,785
  • 4
  • 25
  • 49

2 Answers2

5

django-cors-headers has a signal that allows you to decide whether or not to allow the request to pass. The docs show exactly your use case.

Note that CORS_ORIGIN_WHITELIST is also checked by the cors middleware (the signal response doesn't replace the white list), so you can have both: a static whitelist + a dynamic whitelist that depends on the request. You don't need to check the static whitelist in your signal handler.

dirkgroten
  • 20,112
  • 2
  • 29
  • 42
1

django-cors-headers also has a setting CORS_ALLOWED_ORIGIN_REGEXES, which comes in handy if your allowed origins can be written as a regex / regular expression.

For example, you could use this to allow wildcard subdomains:

CORS_ALLOWED_ORIGIN_REGEXES = [
    r"^https://\w+\.example\.com$",
]
A B
  • 8,340
  • 2
  • 31
  • 35