首页 > 解决方案 > 为什么我的视频没有从 fileField.uploadTo(relative_path) 正确上传并保存在正确的专用目录中?

问题描述

我正在尝试将视频上传到我的 Django 服务器目录。当我在管理面板中使用编码应用程序时,在正确的位置上传成功。但是,在处理浏览器表单时,它会错过一个级别的 url:“media/title.mp4”而不是“media/videos/title.mp4”。

我想将文件保存到“media/videos/title.mp4”中。目前,前面上传的视频 url 计算为“media/title.mp4”。它只是失败了,没有创建资源,即使在错误的位置。

这是我的 urls.py 与上传路线:

from django.urls import path
from uploader.views import upload, download

from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin


urlpatterns = [

    path('admin/', admin.site.urls),
    path('upload/', upload, name='upload'),
    path('download/', download, name='download'),

]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

这是我的上传视图:

from django.shortcuts import render, redirect

from .models import VideoItem

def upload(request):

    if request.method == 'POST':

        title = request.POST['title']
        video = request.POST['video']

        content = VideoItem(title=title, video=video)
        content.save()

    return render(request, 'upload.html')

这是我的上传 html 模板:

<form action="" method="POST">{% csrf_token %}
 
    <input type="text" name="title" placeholder="Enter Video Title here"><br>
    <input type="file" name="video" accept="video/mp4">
    <button type="submit"> Upload New Video </button>
 
</form>

这是我的数据库模型:

from django.db import models
 
# Create your models here.
 
class VideoItem(models.Model):
    title = models.CharField(max_length=100)
    video = models.FileField(upload_to='videos')

    class Meta:
        verbose_name = 'video'
        verbose_name_plural = 'videos'
         
    def __str__(self):
        return self.title

我的媒体根/目录配置(settings.py):

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/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = someSecretKey

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'uploader.apps.UploaderConfig',
]

MIDDLEWARE = [
    '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',
]

ROOT_URLCONF = 'pixblur_project.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 = 'pixblur_project.wsgi.application'


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

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

# Password validation
# https://docs.djangoproject.com/en/2.2/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.2/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/2.2/howto/static-files/

# STATIC FILES (OPTIONAL)

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

STATIC_ROOT = os.path.join(BASE_DIR, 'assets')

# MEDIA FILES

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

有什么提示吗?

标签: pythondjangofile-upload

解决方案


您应该使用request.FILESrequest.POST访问上传的文件。在这里查看更多。

def upload(request):

    if request.method == 'POST':

        title = request.POST['title']
        video = request.FILES['video'] #<-- change it here

        content = VideoItem(title=title, video=video)
        content.save()
    return render(request, 'upload.html')

推荐阅读