¿Why my CORS config in django is not working? - python

I have my REST API settings in my production.py file. This REST API is uploaded to Heroku and uses django-cors-headers with the following configuration:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-Party apps
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'gunicorn',
# Local apps
'core',
'users',
'checkers',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'myapi.herokuapp.com'
)
The idea when putting myapi.herokuapp.com in CORS_ORIGIN_WHITELIST is to see if making the request from localhost is rejected (it would be the right thing to do). But this is accepted which gives me to understand that CORS is not working well.

before fetch the django rest_api, make sure you setup django-cors-headers in your backend settings.py. for more information take a look at this link.
pip install django-cors-headers
settings.py :
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'corsheaders.middleware.CorsPostCsrfMiddleware',
...
]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'your-server-IP-address'
)
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]

Related

Django-debug-toolbar not showing

I am using django 4.0.3 and django-debug-toolbar 3.2.4. For some reason, the toolbar is not showing on my server.I tried many ways but none of them worked for me. I will be very grateful for any help
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'news.apps.NewsConfig',
]
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',
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# debug_toolbar moved here.
if DEBUG:
MIDDLEWARE += [
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
INSTALLED_APPS += [
'debug_toolbar',
]
INTERNAL_IPS = ['127.0.0.1', ]
# this is the main reason for not showing up the toolbar
import mimetypes
mimetypes.add_type("application/javascript", ".js", True)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
urls.py
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
path('__debug__/', include(debug_toolbar.urls)),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your code seems ok to me. Have you tried clearing your browser cache?
In case of Google Chrome, goto Settings>More tools>Clear browsing data... or Ctrl+Shift+Del
You need to add "debug_toolbar" to your INSTALLED_APPS setting.
Docs

Session is not updated after ajax call in django

I'm struggling with session update handle after ajax call in django.
I used database session backend engine. but session is not updated database.
I consider django_session table, but new session wes not inserted after ajax call.
This is my code.
View.py
def contact(request):
contract = request.GET.get('contract ', 1)
contract _session = request.session.get('contract ',False)
if(not contract_session):
request.session['contract '] = Contrato.objects.first().pk
request.session.modified = True
if Contract.objects.filter(id=contract).exists() and contract != request.session['contract ']:
del request.session['contract ']
contract = Contract.objects.get(id=contract)
request.session.set_expiry(180000)
request.session['contract '] = contract .id
request.session.modified = True
request.session.save()
return HttpResponse('ok')
settings.py
SESSION_COOKIE_AGE=3600, # on hour in seconds
INSTALLED_APPS=[
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.humanize',
'rest_framework',
'rest_framework.authtoken',
'rest_framework_jwt',
'django_rest_passwordreset',
'django_filters',
'django_countries',
'corsheaders',
'rest_auth',
'pwa',
],
MIDDLEWARE=[
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'beecoss_api.middleware.LoginRequiredMiddleware',
],
SESSION_ENGINE = "django.contrib.sessions.backends.db",
SESSION_SAVE_EVERY_REQUEST = True,
template.html
var contract= $ ('#contract') .val ();
var url = "{% url 'url'%}";
$ .ajax ({
type: "GET",
url: url,
data: {'contract':contract},
success: function () {}
});
Also I was running server localhost:8000 and 127.0.0.1:8000

django-tenant-schema enable Admin module for all tenants

I am setting up django with multitenant architecture. I went through the https://django-tenant-schemas.readthedocs.io/en/latest/install.html
instruction and get to the point that have inital startup screen.
What I want to achieve is to enable admin module for each tenant.
my in settings.py I have following:
#Application definition
SHARED_APPS = (
'tenant_schemas', # mandatory, should always be before any django app
'customers', # you must list the app where your tenant model resides in
'django.contrib.contenttypes',
# everything below here is optional
)
TENANT_APPS = (
'django.contrib.contenttypes',
# your tenant-specific apps
# 'myapp.hotels',
# 'myapp.houses',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
)
INSTALLED_APPS = [
'tenant_schemas',
'customers',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
]
TENANT_MODEL = "customers.Client"
MIDDLEWARE = [
'tenant_schemas.middleware.TenantMiddleware',
'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 = 'sitemanager.urls'
PUBLIC_SCHEMA_URLCONF = 'sitemanager.urls_public'
when trying to open http://localhost:8000/admin getting error:
DoesNotExist at /admin/login/
Site matching query does not exist.
Request Method: GET
Request URL: http://localhost:8000/admin/login/?next=/admin/
Django Version: 2.1.2
Exception Type: DoesNotExist
Exception Value:
Site matching query does not exist.
my urls.py:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
What am I missing in configuration?
Adding PUBLIC_SCHEMA_NAME = 'public' sort the problem.
I think django.contrib.sites should be in SHARED_APPS.
Kudos for using django-tenant-schema +1
Then to create a superuser :./manage.py tenant_command createsuperuser
Might be handy.

django-cors-headers settings.py django app not working even though I've added all the requirements to settings.py

So, I'm using django-cors-headers with Rest Framework with Django 1.11.x, and I've pretty much followed the general advice, and yet, I'm still getting x has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." As you can see, I've added 'corsheaders' to INSTALLED_APPS and 'corsheaders.middleware.CorsMiddleware' to Middleware, and I've set CORS_ORIGIN_ALLOW_ALL to true and CORS_ALLOW_CREDENTIALS to true, too. I've even included a whitelist option, though it's my understanding that, if CORS_ORIGIN_ALLOW_ALL is set to true, the whitelist isn't needed. I've also pip3 install django-cors-headers. What is the deal??? BTW, I've read the README on the django-cors-headers repo. I want to know why it's not working.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'books.apps.BooksConfig',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = (
'localhost:5555'
)
And my js file that's accessing from localhost:5555 is:
var request = $.ajax({
type: 'GET',
url: url,
dataType: 'json',
xhrFields: {
withCredentials: true
}});

How to get logged in use and protect urls in jwt token auth django REST framework

I have working auth token , working for users on my database at django back end its pretty simple setup using django rest framework and jwt token module. Here is my settings module
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'constants',
'rest_framework_jwt'
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
But know I want my some of my url to authenticate using this token and get to know the logged in user but can't get the materials to do that.
any help .

Categories

Resources