Signup & Login not working in production in DigitalOcean using DjangoRestFramework and getting server error 500

40 Views Asked by At

-I followed the DigitalOcean Documentation to upload my Django app to digitalOcean: https://docs.digitalocean.com/developer-center/deploy-a-django-app-on-app-platform/ And I served my static files and media files using DigitalOcean space and all is good and I can make all of my requests in production but Login & Sign up is only working in my local machine but not in DigitalOcean Server I'm getting server error 500

this is my configuration :

settings.py:

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())

#   set debug to false by default
DEBUG = os.getenv("DEBUG", "False") == "True"

ALLOWED_HOSTS = os.getenv(
"DJANGO_ALLOWED_HOSTS", "www.aklalatshop.com,https://akalat-shopcsphu.ondigitalocean.app").split(",")

# Application definition
INSTALLED_APPS = [
# 'whitenoise.runserver_nostatic',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'egystoreapp',
#   For generating / getting access token
'oauth2_provider',
'social_django',
########################################
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',

#   for social login
'rest_framework_social_oauth2',
#   for digitalOcean space
'storages',
'bootstrap4',
'rest_framework',
'rest_framework.authtoken',

]

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',
'whitenoise.middleware.WhiteNoiseMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware',
]

ROOT_URLCONF = 'egystores.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',
            'django.template.context_processors.media',
            'social_django.context_processors.backends',
            'social_django.context_processors.login_redirect',
        ],
    },
},
]

WSGI_APPLICATION = 'egystores.wsgi.application'

DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") == "True"


if DEVELOPMENT_MODE is True:
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
    }
}
elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic':
if os.getenv("DATABASE_URL", None) is None:
    raise Exception("DATABASE_URL environment variable not defined")
DATABASES = {
    "default": dj_database_url.parse(os.environ.get("DATABASE_URL")),
}

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',
},
],


REST_FRAMEWORK = {

'DEFAULT_PERMISSION_CLASSES': [
    'rest_framework.permissions.AllowAny',
    'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    'rest_framework_social_oauth2.authentication.SocialAuthentication',
],

}


OAUTH2_PROVIDER = {
# this is the list of available scopes
'SCOPES': {'read': 'Read scope'},
'ACCESS_TOKEN_EXPIRE_SECONDS': 36000,
}

OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL = "oauth2_provider.AccessToken"
OAUTH2_PROVIDER_APPLICATION_MODEL = "oauth2_provider.Application"
OAUTH2_PROVIDER_REFRESH_TOKEN_MODEL = "oauth2_provider.RefreshToken"
OAUTH2_PROVIDER_ID_TOKEN_MODEL = "oauth2_provider.IDToken"



#   configurations for digitalocean spaces
AWS_ACCESS_KEY_ID = '******************'

AWS_SECRET_ACCESS_KEY = '******************'

AWS_STORAGE_BUCKET_NAME = '******************'

AWS_S3_ENDPOINT_URL = '******************'

AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}

AWS_DEFAULT_ACL = 'public-read'

AWS_S3_SIGNATURE_VERSION = 's3v4'

STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, 'staticfiles')

MEDIA_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, 'mediafiles')

STATICFILES_STORAGE = 'custom_storages.StaticStorage'

DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'

Serializers.py

class UserSerializer(serializers.ModelSerializer):
#   The Meta class specifies that we are interested
class Meta:
    model = User
    fields = ["id", "first_name", "last_name",
              "username", "password", "email"]
    extra_kwargs = {'password': {'write_only': True}}

apis.py

@permission_classes((AllowAny,))

@csrf_exempt

def user_sign_up(request):

if request.method == "POST":

    #   user data
    serializer = UserSerializer(data=request.POST)
    #   typed username
    username = request.POST.get('username')
    password = request.POST.get('password')
    first_name = request.POST.get('first_name')
    last_name = request.POST.get('last_name')

    #   typed email
    email = request.POST.get('email')
    if User.objects.filter(username=username).exists():
        return JsonResponse({"dublicated username": "your username already exists, try another username"})

    elif User.objects.filter(email=email).exists():
        return JsonResponse({"dublicated email": "your email already exists, try another email"})

    else:

        #   generating access token for each user
        expire_seconds = oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS
        scopes = oauth2_settings.user_settings['SCOPES']
        application = Application.objects.get(name="test_app_name")
        expires = datetime.datetime.now() + timedelta(seconds=expire_seconds)

        if serializer.is_valid():
            user = User.objects.create_user(username, email, password)
            user.first_name = first_name
            user.last_name = last_name
            user.save()
            access_token = AccessToken.objects.create(user=User.objects.all().get(username=username),
                                                      application=application,
                                                      token=generate_token(),
                                                      expires=expires,
                                                      scope=scopes)

            user_type = request.POST.get('user_type')
            if user_type == "driver":
                driver = Driver.objects.get_or_create(
                    user_id=User.objects.all().get(username=username).id)
            elif user_type == "customer":
                customer = Customer.objects.get_or_create(
                    user_id=User.objects.all().get(username=username).id)

            # user_data = []
            # user_data.append(serializer.data)
            # user_data.append(access_token.token)
    return JsonResponse({"registered_user": serializer.data, "access_token": access_token.token})
else:
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

urls.py


path('user/sign_up/', apis.user_sign_up), #=> 
but unfortunately it gave me server error 500 but it works in localhost perfectly
 I don't know where is the problem

Logs Of DigitalOcean ## :

enter image description here

0

There are 0 best solutions below