我正在尝试上传网页到我的django服务器。它们都是我的项目,我希望将来能够通过管理面板添加更多的项目:
我在一个名为projects的应用程序中工作
这是我正在使用的模型:
from django.db import models
from django.utils.timezone import now
from django.core.files.storage import FileSystemStorage
# Create your models here.
class Project(models.Model):
class ProjectType(models.TextChoices):
PYTHON = 'Python'
JAVASCRIPT = 'Javascript'
REACTJS = 'React.js'
REACTNATIVE = 'React Native'
JAVA = 'Java'
C = 'C'
CPP = 'C++'
def upload_location_photo(instance, filename):
return f'photos/projects/{instance.slug}/{filename}'
def upload_location_template(instance, filename):
#I want to get into, app: projects, folder: templates/projects
return f'projects/templates/projects/{instance.slug}/{filename}'
def upload_location_static(instance, filename):
#I want to get into, app: projects, folder: static/projects
return f'projects/static/projects/{instance.slug}/{filename}'
slug = models.CharField(max_length=200, unique=True)
project_type = models.CharField(max_length=50, choices=ProjectType.choices, default=ProjectType.JAVASCRIPT)
title = models.CharField(max_length=150)
description = models.TextField(blank=True)
date_completed = models.DateTimeField(default=now, blank=True)
photo_main = models.ImageField(upload_to=upload_location_photo)
photo_1 = models.ImageField(upload_to=upload_location_photo, blank=True)
photo_2 = models.ImageField(upload_to=upload_location_photo, blank=True)
photo_3 = models.ImageField(upload_to=upload_location_photo, blank=True)
#FILE UPLOAD OF JS APPS
file_html = models.FileField(upload_to=upload_location_template, max_length=100, blank=True)
file_css = models.FileField(upload_to=upload_location_static, max_length=100, blank=True)
file_js = models.FileField(upload_to=upload_location_static, max_length=100, blank=True)
在django的projects中。这个问题是,html, css和js文件被上传到:media/projects/static/projects和media/projects/templates/projects而不是进入我的应用程序,他们被保存在全局媒体文件夹,我怎么能阻止这一点,并直接到我的应用程序的模板和静态文件夹?
对不起,我问这个问题太快了,但是现在我可以帮助别人希望!
我需要添加几行代码:新的进口:
import os
from django.core.files.storage import FileSystemStorage
from django.conf import settings
调整上传位置功能:
def upload_location_template(instance, filename):
return f'{instance.slug}/{filename}'
def upload_location_static(instance, filename):
return f'{instance.slug}/{filename}'
创建新的存储位置,并将它们作为参数添加到我的FileFields:
template_storage = FileSystemStorage(location=os.path.join(settings.BASE_DIR, 'projects/templates/projects/'))
static_storage = FileSystemStorage(location=os.path.join(settings.BASE_DIR, 'projects/static/projects/'))
file_html = models.FileField(upload_to=upload_location_template, storage=template_storage, max_length=100, blank=True)
file_css = models.FileField(upload_to=upload_location_static, storage=static_storage, max_length=100, blank=True)
file_js = models.FileField(upload_to=upload_location_static, storage=static_storage, max_length=100, blank=True)
它现在工作完美,使用这个答案在这里:https://helperbyte.com/questions/177113/django-multiple-media-root