Python Django:将上载的文件保存在特定目录中
我想将用户上载的文件保存在项目目录“media/documents/(其用户id)/filename.pdf”中。我试着这样做:Python Django:将上载的文件保存在特定目录中,python,django,Python,Django,我想将用户上载的文件保存在项目目录“media/documents/(其用户id)/filename.pdf”中。我试着这样做: def user_directory_path(request, filename): return 'user_{0}/{1}'.format(request.user.id, filename) 但我得到了这个错误: 我不知道该怎么办,我有点像个傻瓜。谢谢你的帮助 My models.py: from django.db import models f
def user_directory_path(request, filename):
return 'user_{0}/{1}'.format(request.user.id, filename)
但我得到了这个错误:
我不知道该怎么办,我有点像个傻瓜。谢谢你的帮助
My models.py:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
def user_directory_path(request, filename):
return 'user_{0}/{1}'.format(request.user.id, filename)
class Contract(models.Model):
id = models.AutoField(primary_key = True)
title = models.CharField(max_length=50)
date_created = models.DateTimeField(auto_now_add=True)
file = models.FileField(upload_to=user_directory_path, default = 'settings.MEDIA_ROOT/documents/default.pdf')
class Meta:
ordering = ['-date_created']
def __str__(self):
return self.title
class Employer(AbstractBaseUser):
id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
company_name = models.CharField(max_length=50)
contracts_made = models.ForeignKey(Contract, on_delete=models.CASCADE, default=1)
date_joined = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-date_joined']
def __str__(self):
full_name = str(self.first_name) + " " + str(self.last_name)
return full_name
class Employee(AbstractBaseUser):
id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
date_joined = models.DateTimeField(auto_now_add=True)
agreed = models.ForeignKey(Contract, on_delete=models.CASCADE, default=1)
class Meta:
ordering = ['date_joined']
def __str__(self):
full_name = str(self.first_name) + " " + str(self.last_name)
return full_name
Views.py:
from django.shortcuts import render, redirect
from .forms import UploadFileForm
def HomePageView(request):
return render(request, 'home.html')
def model_form_upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = UploadFileForm()
return render(request, 'model_form_upload.html', {
'form': form
})
Forms.py:
from django import forms
from .models import Contract
class UploadFileForm(forms.ModelForm):
class Meta:
model = Contract
fields = ('title', 'file')
root/settings.py:
"""
Django settings for ContractPal project.
Generated by 'django-admin startproject' using Django 3.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'sdcmn$--+h_392b0-2-jps$zls4!7p+4mq65e=1q6&#p%l1f!!'
# 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',
'contract.apps.ContractConfig',
'django.contrib.sites',
]
SITE_ID = 1
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 = 'ContractPal.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 = 'ContractPal.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/London'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
#CRISPY_TEMPLATE_PACK = 'bootstrap4'
#LOGIN_URL = '/account/login/'
ACCOUNT_ADAPTER = 'invitations.models.InvitationsAdapter'
传递给
upload\u to
的函数不将请求作为第一个参数,而是将模型实例作为第一个参数(请参阅)
如果您希望能够从合同中获取用户
,则必须在合同中保存此信息:
def用户目录路径(实例,文件名):
返回'user{0}/{1}'。格式(instance.user\u id,文件名)
类别合同(models.Model):
id=models.AutoField(主键=True)
user=models.ForeignKey(settings.AUTH\u user\u MODEL,models.PROTECT)
title=models.CharField(最大长度=50)
date\u created=models.DateTimeField(auto\u now\u add=True)
file=models.FileField(上传到=user\u目录\u路径,默认值='settings.MEDIA\u ROOT/documents/default.pdf')
类元:
排序=['-创建日期']
定义(自我):
返回自己的标题
当然,这意味着在创建合同时,还必须传递给用户。例如:
def some_视图(请求、*args、**kwargs):
Contract.objects.create(user=request.user,…)
您无法在默认型号功能中访问请求的用户。callable有两个参数,首先是要保存的实例和上载文件的文件名