Django doesn't load build/static files ReactJS - reactjs

Hello I have try make a website using ReactJS and Django with RESTAPI. When i run npm start and python manage.py runserver
separatly that work perfectly. But when i try to render the index.html with django from the react/build. The files that return 404 exists. It doesn't work. It render a blank page with the errors:
My folders:
There is my files.
settings.py
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = [
"127.0.0.1"
]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'rest_framework.authtoken',
'rest_auth',
'polluser.apps.PolluserConfig',
'restapi.apps.RestapiConfig',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',
]
SITE_ID = 1
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',
'corsheaders.middleware.CorsMiddleware',
]
ROOT_URLCONF = 'template.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'static'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'template.wsgi.application'
...
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
CORS_ORIGIN_ALLOW_ALL = True
ACCOUNT_EMAIL_VERIFICATION = "none"
ACCOUNT_AUTHENTICATION_METHOD = "username"
ACCOUNT_EMAIL_REQUIRED = False
urls.py
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
urlpatterns = [
path('', TemplateView.as_view(template_name="build/index.html")),
path('admin/', admin.site.urls),
path('api/', include('restapi.urls')),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
]

Try to run python manage.py collectstatic command once and check.
Error 404 occur when you request a resource which is not present in the location you are pointing. make sure the request files to be present in <your-project>/static/ folder. static/ directory is along side manage.py file.
If you are passing authorization header in API request. Then make sure it is not forwarded in other request server make to fetch static resource. (Try making request on page without authorization in header and see if same error occurs.)
If you are required to pass authorization to access those resouce then try passing authorization in request header.

Related

django sitemap for static react routes (error : NoReverseMatch at /sitemap.xml/)

i want to implement sitemap for static react routes and I get this error:
Reverse for 'contact' not found. 'contact' is not a valid view function or pattern name.
I added a list of my react routes REACT-ROUTES in settings.py and append them to urlpatterns in the root urls.py file
settings :
REACT_ROUTES = [
'contact',
'politique-de-confidentialite',
'mentions-legales',
'cookies',
.
.
]
INSTALLED_APPS = [
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.sitemaps',
'rest_framework',
.
.
]
SITE_ID = 1
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'ess')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_URL = '/static/'
STATIC_ROOT = basepath + '/app/static'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ess', 'static')]
urls :
from django.conf import settings
from django.contrib.sitemaps.views import sitemap
from .sitemaps import StaticViewSitemap
react_routes = getattr(settings, 'REACT_ROUTES', [])
sitemaps = {
'static': StaticViewSitemap
}
urlpatterns = [
path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
re_path(r'^$', TemplateView.as_view(template_name='index.html')),
]
for route in react_routes:
urlpatterns += [
re_path('{}'.format(route), TemplateView.as_view(template_name='index.html'))
]
sitemaps.py :
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
class StaticViewSitemap(Sitemap):
def items(self):
return ['contact']
def location(self, item):
return reverse(item)
I don't know what I am missing, please help
I solved the problem by adding a sitemap.xml file inside my react build folder
then added in urlpatterns
path('sitemaps.xml/',TemplateView.as_view(template_name='sitemap.xml', content_type='text/xml'),

Django: Acess denied to XMLHttp request from react because of CORS policy

I am using django as backend and using react in the fronted and I recieve a problem when I try to access data from django server. When I open devtools I recieve the error:
Access to XMLHttpRequest at 'http://localhost:8000/wel' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
my settings.py:
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-vmainp*+c^_!0*f50a09f+)txe6wjt!#pge7%$#ak(=i*a4in*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*"]
CORS_ORIGIN_ALLOW_ALL = True
# Application definition
INSTALLED_APPS = [
'rest_framework',
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core',
]
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',
'corsheaders.middleware.CorsMiddleware'
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny' ],
'CORS_ORIGIN_ALLOW_ALL' : True
}
ROOT_URLCONF = 'middleware.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'middleware.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
How come I recieve an error when I allowed all origins?

Django CORS requests creating 403 Forbidden Error only on server

I have an application which uses Django for the backend and react for the frontend so I setup django-cors-headers. When I tested the application locally with the settings I added, I had no issues. But I deployed to my server, I kept getting 403 error on API requests (except GET requests).
Below is my settings.py file (only the relevant settings):
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<my-secret-key>'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['<my-server-ip>']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'frontend',
'services',
'rest_framework',
'dj_rest_auth',
'rest_framework.authtoken',
'user',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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',
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
}
CORS_ALLOWED_ORIGINS = [
"http://<my-server-ip>:8000",
"http://localhost:8000",
"http://127.0.0.1:8000",
"http://0.0.0.0"
]
CSRF_TRUSTED_ORIGINS = [
"http://<my-server-ip>:8000",
"http://localhost:8000",
"http://127.0.0.1:8000",
"http://0.0.0.0"
]
CORS_ALLOW_CREDENTIALS = True
I make the API requests from React using axios in the form axios.post('http://:8000/api-endpoint', body, config) with then and catch blocks.
The specific errors that I am getting are:
xhr.js:177 POST http://<my-server-ip>:8000/api/auth/login/ 403 (Forbidden)
and
createError.js:16 Uncaught (in promise) Error: Request failed with status code 403
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
Thanks to dbuchet, I found that the problem here was not CORS, rather the fact that in my settings.py file, I had both session and token authentication listed as the default authentication classes - removing the session authentication class fixed the problem I was having.

Deploying Django REST app on Google App Engine gives 502 Error

I have a Django REST application that I managed to deploy to Google App Engine flexible environment (python 3) (https://cloud.google.com/python/django/flexible-environment)
The deployment went fine and I can run the app locally with Cloud SQL proxy. However, when I browse to the provided URL I get a 502 Error:
Error: Server Error
The server encountered a temporary error and could not complete your
request.
Please try again in 30 seconds.
There is no error in the logs, so I can figure out what is going wrong.
In the console I get
GET https://*.appspot.com/ 502 ()
GET https://*.appspot.com/favicon.ico 502 ()
If anyone has experienced something like this, please give me some pointers.
Including app.yaml:
# [START runtime]
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT myapp_api.wsgi
beta_settings:
cloud_sql_instances: test-project:europe-west1:test-db
runtime_config:
python_version: 3
# [END runtime]
Including settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '...'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
'oauth2_provider',
'rest_framework_tracking',
'accounts'
]
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',
'corsheaders.middleware.CorsMiddleware',
]
ROOT_URLCONF = 'myapp_api.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'accounts/templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages'
],
},
},
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
}
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
WSGI_APPLICATION = 'myapp_api.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'test',
'USER': 'foo',
'PASSWORD': 'password'
}
}
DATABASES['default']['HOST'] = '/cloudsql/test-project:europe-west1:test-db'
if os.getenv('GAE_INSTANCE'):
pass
else:
DATABASES['default']['HOST'] = '127.0.0.1'
DATABASES['default']['PORT'] = '5432'
AUTH_PASSWORD_VALIDATORS = [ ... ]
PASSWORD_HASHERS = [ ... ]
LOGGING = {
'version': 1, ...
}
STATIC_URL = 'https://storage.googleapis.com/test-bucket/static/'
STATIC_ROOT = 'static/'
FAVICON_PATH = STATIC_URL + 'favicon.ico'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "myapp_api", "img")
]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
)
CORS_ORIGIN_REGEX_WHITELIST = (
r'^(https?://)?localhost',
r'^(https?://)?127.',
)
OAUTH2_PROVIDER = {
'ACCESS_TOKEN_EXPIRE_SECONDS': 3600
}
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Adding the allowed hosts list should fix the issue.
ALLOWED_HOSTS = ['*']

Template changes after installing django-allauth?

I am trying to install Django-rest-auth + registration. In the docs, it says to install Django-allauth which I did following the steps found here. However, once I did and migrated, my app seemed to be using a different template than the one I had set up originally.
I am using Django Rest Framework and Angular JS.
settings.py
INSTALLED_APPS = [
...
# Django Rest Framework
'rest_framework',
'rest_framework.authtoken',
# All auth
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
# Rest auth
'rest_auth',
'rest_auth.registration',
# My app
'myapp',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
# `allauth` needs this from django
'django.template.context_processors.request',
],
},
},
]
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
)
SITE_ID = 1
My urls.py in my project folder looks like this:
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
# My api url
url(r'^api/', include('myapp.urls')),
# My application url
url(r'^$', TemplateView.as_view(template_name='base.html')),
# all auth Url
url(r'^accounts/', include('allauth.urls')),
# Rest-auth url
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
]
Before installing the all-auth app, going to 127.0.0.1:8000 returned a page using the base.html file. However, now I get a page with the following things:
Menu:
Link to Change E-mail
Sign out
What am I doing wrong? and how do I fix the problem. Thanks.
Any help is greatly appreciated!

Resources