如何在django中的cPanel中上传图片?

时间:2019-02-15 18:52:16

标签: python django python-3.x django-models django-1.8

操作系统== CentOS7

Python == 3.6.5

Django == 1.8

我的Django项目中有一个“新闻”应用程序。并在此应用程序的模型中具有ImageField。尝试在django管理界面中上传.jpg格式的图片,该图片位于cPanel中。但是只要上传栏完成100%,它就会把我带到“未找到”页面,并说在此服务器上找不到请求的URL/admin/news/post/add/。

我认为这是服务器端的问题,但是当与托管服务提供商的支持团队联系时。他们说这不是他们的代码方面的问题。没有任何Apache或Nginx的许可。操作系统

主要 urls.py

# from django.urls import path
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.static import serve

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^news/', include('news.urls')),
    url(r'^i18n/', include('django.conf.urls.i18n')),
]

if settings.DEBUG is False:
    urlpatterns += [
        url(r'^media/(?P<path>.*)$', serve, {
        'document_root' : settings.MEDIA_ROOT,}),
    ]

(新闻)应用url, news / urls.py

from . import views

urlpatterns =[
    url(r'^$', views.NewsView.as_view(), name='posts'),
    url(r'^i18n/', include('django.conf.urls.i18n')),
    url(r'^index', views.search, name="search"),
    url(r'^chaining/', include('smart_selects.urls')),
    url(r'^league/(?P<pk>[0-9]+)/$', views.league_detail, name='league_detail'),
]

(新闻)应用程序 models.py 注意!错误发生在 Post 类的ImageField中:

# from django.contrib.auth.models import User
from django_userforeignkey.models.fields import UserForeignKey
# import datetime
# from django.utils.six import with_metaclass
# from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_delete
from django.dispatch import receiver

# excelFile = open('news/static/excelFile/table.csv', 'r').read()
# newEntry = excelToDB(someField=excelFile)
from smart_selects.db_fields import ChainedForeignKey

POSITIONS = (
    ('Darvozabon', 'Darvozabon'),
    ('Himoyachi', 'Himoyachi'),
    ('Yarim Himoyachi', 'Yarim Himoyachi'),
    ('Hujumchi', 'Hujumchi'),
)


class League(models.Model):
    name = models.CharField(max_length=255, unique=True)
    description = models.CharField(max_length=255)
    abbrv = models.CharField(max_length=10, unique=True)

    def __str__(self):
        return self.name


class Club(models.Model):
    league = models.ForeignKey(League, on_delete=models.CASCADE, related_name='clubs')
    name = models.CharField(max_length=50)
    coachName = models.CharField(max_length=80)
    abbrv = models.CharField(max_length=10, unique=True)
    description = models.CharField(max_length=255)

    def __str__(self):
        return self.name


class Player(models.Model):
    league = models.ForeignKey(League, on_delete=models.CASCADE, related_name='player')
    club = ChainedForeignKey(
        Club,  # the model where you're populating your countries from
        chained_field='league',  # the field on your own model that this field links to
        chained_model_field='league',  # the field on Country that corresponds to newcontinent
        show_all=False,  # only shows the countries that correspond to the selected continent in newcontinent
    )
    firstName = models.CharField(max_length=50, unique=True)
    lastName = models.CharField(max_length=50, unique=True)
    age = models.IntegerField()
    goalsLeague = models.IntegerField()
    pNumber = models.IntegerField()
    position = models.CharField(max_length=20, choices=POSITIONS, unique=True)

    def __str__(self):
        return self.firstName + " " + self.lastName + " " + self.club.name


class Post(models.Model):
    league = models.ForeignKey(League, on_delete=models.CASCADE, related_name='posts', blank=True, null=True)
    club = ChainedForeignKey(
        Club,  # the model where you're populating your countries from
        chained_field='league',  # the field on your own model that this field links to
        chained_model_field='league',  # the field on Country that corresponds to newcontinent
        show_all=False,  # only shows the countries that correspond to the selected continent in newcontinent
        blank=True,
        null=True,
    )
    player = ChainedForeignKey(
        Player,  # the model where you're populating your countries from
        chained_field='club',  # the field on your own model that this field links to
        chained_model_field='club',  # the field on Country that corresponds to newcontinent
        show_all=False,  # only shows the countries that correspond to the selected continent in newcontinent
        blank=True,
        null=True,
    )
    title = models.CharField(max_length=255)
    body = models.TextField(max_length=4000)
    img = models.ImageField()
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = UserForeignKey(auto_user_add=True, verbose_name='The user that is automatically assigned', related_name='posts')

    def __str__(self):
        return self.title


@receiver(post_delete, sender=Post)
def submission_delete(sender, instance, **kwargs):
    instance.img.delete(False)

settings.py:

from django.utils.translation import ugettext_lazy as _

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = "/media/"

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
STATIC_URL = '/static/'
STATIC_ROOT = 'news/static/'
STATICFILES_DIRS =(
    os.path.join(BASE_DIR,'news/static/images'),
)
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xxxxxx'

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

ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'www.favourite.uz', 'favourite.uz']


# Application definition

INSTALLED_APPS = [
    'modeltranslation',
    'news.apps.NewsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_userforeignkey',
    'simplesearch',
    'smart_selects',
]

MIDDLEWARE_CLASSES = [
    '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',
    'django_userforeignkey.middleware.UserForeignKeyMiddleware',
    'django.middleware.locale.LocaleMiddleware',
]

LANGUAGES = (
    ('en', _('Uzbek')),
    ('ru', _('Русский')),
)

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

# MODELTRANSLATION_DEFAULT_LANGUAGE = 'en'
# MODELTRANSLATION_TRANSLATION_REGISTRY = 'news.translation'

ROOT_URLCONF = 'futbik_version_7.urls'

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

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.i18n',
)

WSGI_APPLICATION = 'futbik_version_7.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# SOUTH_DATABASE_ADAPTERS = {
#     'default': 'south.db.sqlite3'
# }

# Password validation
# https://docs.djangoproject.com/en/2.0/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/2.0/topics/i18n/

LANGUAGE_CODE = 'en'

TIME_ZONE = 'Asia/Tashkent'

USE_I18N = True

USE_L10N = True

USE_TZ = True

USE_DJANGO_JQUERY = False


# MODELTRANSLATION_DEBUG = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

我想知道是否可以在cPanel中开发类似Django的项目。使用它的原因是成本。我今天买不起VPS或VDS。因此,如果有人遇到这种情况,我需要帮助!我感谢您的帮助!
P.s。我是Django的初学者!

0 个答案:

没有答案