Как загрузить изображение в cPanel в Django? - PullRequest
0 голосов
/ 15 февраля 2019

OS == CentOS7

Python == 3.6.5

Django == 1.8

У меня есть приложение "новости" в моем проекте Django.И в моделях этого приложения есть ImageField.Пытаясь загрузить изображение в формате .jpg в интерфейсе администратора django, оно находится в cPanel.Но всякий раз, когда загрузка бара завершается на 100%, он переходит на страницу «Не найдено» и сообщает, что Запрошенный URL / admin / news / post / add / не был найден на этом сервере.

Я думал, что это проблема на стороне сервера, но когда связался со службой поддержки провайдера хостинга.Они сказали, что это проблема кода, а не их.Нет разрешения ни на apache, ни на nginx.OS

Main 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 class'es 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/

IИнтересно, можно ли разрабатывать Django как проекты в cPanel.Причиной использования этого является стоимость.Я не могу позволить себе VPS или VDS на сегодня.Поэтому мне нужна помощь, если кто-то сталкивался с такой ситуацией!Я ценю вашу помощь!
Ps Я начинающий в Джанго!

...