23246

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

Question:

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!

<strong>Here's my settings.py:</strong>

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

<strong>And Here's my view which throws Server Error(5005):</strong>

<strong>From views.py:</strong>

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

Answer1:

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: <a href="https://cloud.google.com/python/monitor-and-debug/logging-application-events" rel="nofollow">https://cloud.google.com/python/monitor-and-debug/logging-application-events</a>

Details about exception handling: <a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow">https://docs.python.org/3/tutorial/errors.html</a>

*** 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.

Recommend

  • Django AttributeError 'float' object has no attribute 'split'
  • Amazon S3 to store Wagtail media files - server 500 error on Heroku only
  • django-import-export: cannot exclude id field during import : KeyError: u'id'
  • Django REST Framework w/ TokenAuthentication issue with CSRF/CORS
  • Reverse for 'password_change_done' with arguments '()' and keyword arguments �
  • Using string.matches to check if last character is vowel
  • Does TideSDK have any image manipulation capabilities?
  • Fieldable.tokenStreamValue() returns null for tokenized field
  • simplexml and accessing feedburner's : [duplicate]
  • Bootstrap - Scrollspy scrolling skipping second to last section
  • Safari blurs strange bugs
  • Extending the User Interface in Outlook 2010 to add to the Right Click menu
  • Localization laravel
  • Dynamic Sieve Algorithms for Prime Generation
  • Issue with Route Protection in Laravel 5.3
  • Query azure table by collection of row keys
  • Azure Cosmos DB check if array in field is contained in search array
  • Is it mandatory to use Kony middleware for Kony application?
  • Scroll to anchor link in a Sammy.js project
  • SQL: Find top-rated article in each category
  • Windows service showing a GUI when no user is logged in
  • Autofac with ASP.NET Identity in MVC 5 does not validate Security Stamp in OWIN pipeline
  • C++ face detection/recognition implementations
  • Using publish-composite with Angular-Meteor
  • Multiple auth user types in Laravel 5
  • Categories and SubCategories
  • Qt — pass events to multiple objects?
  • Is there a better method than to reuse a complicated table in DocBook?
  • Fast way to alphabetically sort the contents of a file in java
  • What dll is needed for Windows.Devices.Geolocation?
  • SQL append distinct values from two columns and two tables
  • HALF_PTR Windows data type
  • Local Development, Apache vs Developer - file permissions
  • Embedded Glassfish JPA Datasource connection fail
  • HttpListener.IsSupported is false on XP SP3
  • JQuery .html() remove line break on IE 8
  • Enabling DTD support in Sql Server
  • GAE: Way to get reference to an HttpSession from its ID?
  • Does Mobilefirst provide a provision to access web services directly?
  • How to get icons for entities from eclipse?