0

I am trying to deploy a django react ecommerce app using aws ec2. when i run python manage.py runserver 0.0.0.0:8000 it is loading the page but not serving static files. The errors are

[24/Jun/2021 19:29:26] "GET / HTTP/1.1" 200 2297
[24/Jun/2021 19:29:26] "GET /static/css/2.97503911.chunk.css HTTP/1.1" 404 179
[24/Jun/2021 19:29:26] "GET /static/css/main.4586955f.chunk.css HTTP/1.1" 404 179
[24/Jun/2021 19:29:26] "GET /static/js/2.7e7fd32c.chunk.js HTTP/1.1" 404 179
[24/Jun/2021 19:29:26] "GET /static/js/main.002fbd2b.chunk.js HTTP/1.1" 404 179

Here is my settings.py file

"""
Django settings for backend project.

Generated by 'django-admin startproject' using Django 3.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
from datetime import timedelta

# 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.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+^5qu3r54+4ja6q(_$rc!w4*z9t$erk61j=m8wbry53y*c-&h*'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

CORS_ORIGIN_ALLOW_ALL = False

CORS_ALLOWED_ORIGINS = ['http://localhost:3000']

CORS_ALLOW_CREDENTIALS = True

ALLOWED_HOSTS = ['myamazonclone.ml']

SITE_ID = 1

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'dj_rest_auth',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'dj_rest_auth.registration',
    'rest_framework_simplejwt.token_blacklist',
    'users',
    'payment',
    'products',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny'
    ],

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
    )

}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': True,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    # 'SIGNING_KEY': settings.SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,

    'AUTH_HEADER_TYPES': ('Bearer', 'JWT'),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=60),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

REST_USE_JWT = True

JWT_AUTH_COOKIE = 'my-app-auth'
JWT_AUTH_REFRESH_COOKIE = 'users-refresh-token'

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',
    'django.middleware.common.CommonMiddleware',
]

ROOT_URLCONF = 'backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR/'frontend'],
        '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 = 'backend.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/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.1/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.1/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR/'static'
STATICFILES_DIRS = [BASE_DIR/'frontend/static']

AUTH_USER_MODEL = 'users.User'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False

# E-mail address is automatically confirmed by a GET request
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
# Allow logins with an unverified e-mail address
ACCOUNT_EMAIL_VERIFICATION = 'none'

# REST_AUTH_REGISTER_SERIALIZERS = {
#     'REGISTER_SERIALIZER': 'users.serializers.CustomRegistrationSerializer'
# }

AUTHENTICATION_BACKENDS = [
    'allauth.account.auth_backends.AuthenticationBackend',
    'django.contrib.auth.backends.ModelBackend',
]

I have mentioned the STATIC_ROOT above and have also done python manage.py collectstatic. After doing so it makes a static folder in the root where manage.py is located and it also contains all the files the django is unable to find and gives 404. I also tried using gunicorn but still it is not able to serve static files. I donot understand what mistake i am making . Any help will be really appriciated. Here is my file structure

Amazon Prod
├─ backend
│  ├─ asgi.py
│  ├─ settings.py
│  ├─ urls.py
│  ├─ wsgi.py
│  ├─ __init__.py
│  └─ __pycache__
│     ├─ settings.cpython-39.pyc
│     ├─ urls.cpython-39.pyc
│     ├─ wsgi.cpython-39.pyc
│     └─ __init__.cpython-39.pyc
├─ db.sqlite3
├─ frontend
│  ├─ asset-manifest.json
│  ├─ favicon.ico
│  ├─ index.html
│  ├─ logo192.png
│  ├─ logo512.png
│  ├─ manifest.json
│  ├─ robots.txt
│  └─ static
│     ├─ css
│     │  ├─ 2.97503911.chunk.css
│     │  ├─ 2.97503911.chunk.css.map
│     │  ├─ main.4586955f.chunk.css
│     │  └─ main.4586955f.chunk.css.map
│     └─ js
│        ├─ 2.7e7fd32c.chunk.js
│        ├─ 2.7e7fd32c.chunk.js.LICENSE.txt
│        ├─ 2.7e7fd32c.chunk.js.map
│        ├─ main.002fbd2b.chunk.js
│        ├─ main.002fbd2b.chunk.js.map
│        ├─ runtime-main.e2a9cdff.js
│        └─ runtime-main.e2a9cdff.js.map
├─ manage.py
├─ payment
├─ products
├─ requirements.txt
├─ static
└─ users

backend is the name of project. frontend is the production build react app.

here is my project urls.py file

from django import urls
from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)
from users.views import BlacklistTokenUpdateView

# Allows to render a template without a view
from django.views.generic import TemplateView


urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('rest_framework.urls')),
    path('dj-rest-auth/', include('dj_rest_auth.urls')),
    path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('blacklist/', BlacklistTokenUpdateView.as_view(), name='blacklist'),
    path('payment/', include('payment.urls')),
    path('storeApi/', include('products.urls')),
    path('', TemplateView.as_view(template_name='index.html'))
]

1 Answers1

0

Check the ownership of the files. If you load your files as ec_user and try to deliver as www-data with 640 permissions you will have 404s. wild bet.

alabalistic
  • 169
  • 2