I have made an instagram like django app that works perfectly fine locally, however after I deployed the app to heroku, whenever I try to upload and save a photo, I get an internal server error(500). I am using the Uploadcare API to upload and save photos. I am not sure how to fix this problem.
the photos below are the heroku logs i get.
this is my models.py
from django.db import models
class ValidationInfo(models.Model):
val_school_id = models.CharField(max_length=5)
val_school_pass = models.CharField(max_length=10)
class User(models.Model):
is_authenticated = True
school_name = models.CharField(max_length=50,default="")
school_id = models.CharField(max_length=50,default="")
password = models.CharField(max_length=100)
email = models.CharField(max_length=100)
username = models.CharField(max_length=20)
sign_up_date = models.DateTimeField(auto_now=True)
last_login = models.DateTimeField(auto_now=True)
profilepic = models.CharField(max_length=255, default="")
class Photo(models.Model):
baseurl = models.CharField(max_length=255)
url = models.CharField(max_length=255)
date_uploaded = models.DateTimeField(auto_now=True)
owner = models.CharField(max_length=20)
likes = models.IntegerField()
caption = models.CharField(max_length=140, default="")
tags = models.IntegerField(default=0)
main_colour = models.CharField(max_length=15, default="")
owner_school = models.CharField(max_length=30, default="")
class PhotoLikes(models.Model):
postid = models.IntegerField()
liker = models.CharField(max_length=20)
class Followers(models.Model):
user = models.CharField(max_length=20, default="")
follower = models.CharField(max_length=20, default="")
class PhotoTag(models.Model):
photoid = models.IntegerField()
coords = models.CharField(max_length=40)
tagged_user = models.CharField(max_length=20, default="")
tagged_by = models.CharField(max_length=20, default="")
this is my Ajax and AjaxSavePhoto class in forms.py
class Ajax(forms.Form):
args = []
user = []
def __init__(self, *args, **kwargs):
self.args = args
if len(args) > 1:
self.user = args[1]
if self.user.id == None:
self.user = "NL"
def error(self, message):
return json.dumps({ "Status": "Error", "Message": message }, ensure_ascii=False)
def success(self, message):
return json.dumps({ "Status": "Success", "Message": message }, ensure_ascii=False)
def items(self, json):
return json
def output(self):
return self.validate()
class AjaxSavePhoto(Ajax):
def validate(self):
try:
self.url = self.args[0]["url"]
self.baseurl = self.args[0]["baseurl"]
self.caption = self.args[0]["caption"]
except Exception as e:
return self.error("問題が発生しました。やり直してください。")
if self.user == "NL":
return self.error("写真をアップロードするにはログインしてください。")
if len(self.caption) > 140:
return self.error("キャプションは140文字以内である必要があります。")
if self.url[0:20] != "https://ucarecdn.com" or self.baseurl[0:20] != "https://ucarecdn.com":
return self.error("Invalid image URL")
result = urlopen(self.baseurl+"-/preview/-/main_colors/3/")
data = result.read()
data = json.loads(data.decode('utf-8'))
main_colour = ""
if data["main_colors"] != []:
for colour in data["main_colors"][randint(0, 2)]:
main_colour = main_colour + str(colour) + ","
main_colour = main_colour[:-1]
result = urlopen(self.baseurl+"detect_faces/")
data = result.read()
data = json.loads(data.decode('utf-8'))
tag_count = 0
p = Photo(url=self.url, baseurl=self.baseurl, owner=self.user.username, owner_school=self.user.school_name, likes=0, caption=self.caption, main_colour=main_colour)
p.save()
if data["faces"] != []:
for face in data["faces"]:
tag = PhotoTag(photoid=p.id, coords=face).save()
tag_count = len(data["faces"])
p.tags = tag_count
p.save()
return self.success("Image Uploaded")
and this is my settings.py
"""
Django settings for instapic project.
Generated by 'django-admin startproject' using Django 1.11.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'er7!))(no=x)g%y(qi1x*jj3*9)y-#3__0bwa*_j0d_l-r_%9q'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'instapic',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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',
]
ROOT_URLCONF = 'instapic.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 = 'instapic.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "instapic",
"USER": "dj.usagi",
"PASSWORD": "drsm0619",
"HOST": "localhost",
"PORT": "",
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/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.11/topics/i18n/
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
AUTHENTICATION_BACKENDS = ( 'instapic.authb.AuthB', )
# Heroku: Update database configuration from $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Thank you in advance.
According to your error logs, the problem is saving data that does not fit into your DB schema. There is no
owner_prefectrure
field in your models though. Make sure that you migrate your schema properlynot related to the problem, but you could try to use
pyuploadcare
's Django package to store uploaded images. This should simplify your code significantly.