使用部署到Heroku的Django应用程序时出现内部服务器错误。该应用在本地运作

时间:2017-12-31 08:50:44

标签: python django heroku internal-server-error uploadcare

我已经创建了一个像django app这样的Instagram,在本地运行得非常好,但是在我将应用程序部署到heroku之后,每当我尝试上传并保存照片时,我都会收到内部服务器错误(500)。我正在使用Uploadcare API上传和保存照片。我不知道如何解决这个问题。

下面的照片是我得到的heroku日志。

这是我的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="")

这是我在forms.py

中的Ajax和AjaxSavePhoto类
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")

这是我的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'

提前谢谢。

1 个答案:

答案 0 :(得分:1)

  1. 根据您的错误日志,问题是保存的数据不适合您的数据库架构。但是您的模型中没有owner_prefectrure字段。确保正确migrate您的架构

  2. 与问题无关,但您可以尝试使用pyuploadcare的Django包来存储上传的图片。这应该会显着简化您的代码。