Python 在Django中尝试上载图像时,没有此类文件或目录
我在配置文件模型上有一个ImageField,用户可以上传图像。但是,当我尝试上载图像时,会出现以下错误:Python 在Django中尝试上载图像时,没有此类文件或目录,python,django,Python,Django,我在配置文件模型上有一个ImageField,用户可以上传图像。但是,当我尝试上载图像时,会出现以下错误:FileNotFoundError:[Errno 2]没有这样的文件或目录:“C:\\Users\\name\\Documents\\Projects\\project\\media\\image.png”。当我查看数据库时,profile_image字段会显示为“image.png”,但该文件不会出现在项目中的任何文件夹中 设置.py STATIC_ROOT = os.path.join(
FileNotFoundError:[Errno 2]没有这样的文件或目录:“C:\\Users\\name\\Documents\\Projects\\project\\media\\image.png”
。当我查看数据库时,profile_image字段会显示为“image.png”,但该文件不会出现在项目中的任何文件夹中
设置.py
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
DEBUG_PROPAGATE_EXCEPTIONS = True
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
url.py
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
def validate_image(image):
file_size = image.file.size
limit_kb = 1000
if file_size > limit_kb * 1024:
raise ValidationError("Max size of file is %s KB" % limit_kb)
class Profile(models.Model):
...
profile_image = models.ImageField(upload_to='profile_images/', blank=True, null=True, validators=[validate_image])
views.py
profile_form = ProfileForm(request.POST, request.FILES, instance=profile)
updatedProfile = profile_form.save(commit=False)
updatedProfile.save()
currentuser.email = request.POST['email']
currentuser.save()
messages.success(request, 'Profile successfully updated!')
return redirect('viewprofile', slug=profile)
forms.py
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['profile_image', ...]
模板
<label for="profile_image">Profile Image (size cannot exceed 1 MB)</label></p>
<input id="profile_image" type="file" class="" name="profile_image">
配置文件映像(大小不能超过1 MB)
使用
您是否包含了enctype='multipart/form data
?不,这是怎么回事?在输入表单中?我会给它一个tryYes,你需要包括这当你使用的形式,有一个文件上传控制,否则它将不工作是的,谢谢!