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
Related
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',
]
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.
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
}});
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 .
I'm trying to retrieve the json from the rest api set up using Django.
This data is currently only hosted on: http://127.0.0.1:8000/xyz
When I try to retrieve it using
$http({
method: 'GET',
url: 'http://127.0.0.1:8000/xyz',
})
I get an error that is:
XMLHttpRequest cannot load http://127.0.0.1:8000/xyz. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access.
Can someone tell me a way of dealing with this, please?
Thanks!
Here's my Django settings folder:
INSTALLED_APPS = (
'student',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders'
)
MIDDLEWARE_CLASSES = (
'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',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware'
)
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api.*$'
CORS_ORIGIN_WHITELIST = (
'mydomain',
'localhost:3000',
'http://127.0.0.1:8000/'
)
Look into using django-cors-headers to have Django return the proper headers. You can then create a whitelist for your site (http://127.0.0.1:8080 for development and whatever your final domain for production)
I use the following on my settings for a similar setup:
INSTALLED_APPS += ('corsheaders',)
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api.*$'
CORS_ORIGIN_WHITELIST = (
'mydomain',
'localhost:3000',
)
You may also need to add the following to your Angular project:
$http.defaults.useXDomain = true;
[UPDATE]
See this blog for more details
Apart from the changes in settings.py, please try to add a slash at the end of the url you are calling
$http({
method: 'GET',
- url: 'http://127.0.0.1:8000/xyz',
+ url: 'http://127.0.0.1:8000/xyz/',
})