Search code examples
pythondjangogoogle-cloud-platformgunicorninternal-server-error

Django on Production for POST request throws Server Error(500) on compute engine


I have deployed my Django 1.10 with python 3.6 Project on Google compute engine when I have changed Debug = True in my settings.py to Debug = False it throws Server Error (500) on one of my post requests.Even other post requests like signup are working fine. When I stop gunicorn process and re-run it again then this POST works for few hours and again start throwing Server Error(500).

How can I solve this issue as I'm using Django 1.10.5, Python 3.6 on Compute Engine? Help me, please! Thanks in Advance!

Here's my settings.py:

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__)))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*************************'

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

ALLOWED_HOSTS = ['127.0.0.1', 'brainresearchtagging.com']
# INTERNAL_IPS = ['127.0.0.1']

# Application definition

INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'debug_toolbar',
   'users',
   'article',
   'import_export',
]
MIDDLEWARE = [
   'django.middleware.security.SecurityMiddleware',
   'whitenoise.middleware.WhiteNoiseMiddleware',
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django.middleware.common.CommonMiddleware',
   'debug_toolbar.middleware.DebugToolbarMiddleware',
   'django.middleware.csrf.CsrfViewMiddleware',
   'django.contrib.auth.middleware.AuthenticationMiddleware',
   'django.contrib.messages.middleware.MessageMiddleware',
   'django.middleware.clickjacking.XFrameOptionsMiddleware',
  ]

ROOT_URLCONF = 'brain.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'brain.wsgi.application'

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASS',
        'HOST': 'IP',
        'PORT': '5432',
   }
} 


#Static Storage
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

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

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/assets/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets'), ]


# Authentication
LOGIN_URL = 'users:login'
LOGIN_REDIRECT_URL = 'users:dashboard'

EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = os.path.join(BASE_DIR, 'emails')

# Django Import-Export
IMPORT_EXPORT_USE_TRANSACTIONS = True

And Here's my view which throws Server Error(5005):

From views.py:

class TagView(LoginRequiredMixin, generic.CreateView):
form_class = forms.TagForm

def post(self, request, *args, **kwargs):
    if request.method == 'POST':
        post_data = request.POST.copy()
        post_data.update({'user': request.user.pk})
        form = forms.TagForm(post_data)
        if form.is_valid():
            print(form.errors)
            tag = form.save(commit=False)
            tag.user = request.user
            tag.email = request.user.email
            tag.save()
        else:
            return HttpResponse(form.errors, status=400)

        return HttpResponseRedirect(reverse_lazy('users:dashboard'))

Solution

  • As discussion above from comments, you can put exception handling in code and put logger in the code. For example:

    import logging
    
    
    class TagView(LoginRequiredMixin, generic.CreateView):
        form_class = forms.TagForm
    
        def post(self, request, *args, **kwargs):
            try:
                post_data = request.POST.copy()
                post_data.update({'user': request.user.pk})
                form = forms.TagForm(post_data)
                if form.is_valid():
                    tag = form.save(commit=False)
                    tag.user = request.user
                    tag.email = request.user.email
                    tag.save()
                else:
                    return HttpResponse(form.errors, status=400)
    
                return HttpResponseRedirect(reverse_lazy('users:dashboard'))
    
            except Exception as exp:
              logging.error(exp)  # For python 3
              return HttpResponse(exp, status=400)
    

    And view the error logs using log monitoring tool like this blog mentioned: https://cloud.google.com/python/monitor-and-debug/logging-application-events

    Details about exception handling: https://docs.python.org/3/tutorial/errors.html

    *** As per discussion in the comments in the answer, the problem resides in ALLOWED_HOSTS. Setting ALLOWED_HOSTS=['*'] or Setting the IP of the Server in Allowed Host solved the issue.