【问题标题】:No such file or directory when trying to upload images in Django尝试在 Django 中上传图像时没有这样的文件或目录
【发布时间】:2020-08-03 22:06:27
【问题描述】:

我在 Profile 模型上有一个 ImageField,因此用户可以上传图片。但是,当我尝试上传图片时,出现此错误:FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\name\\Documents\\Projects\\project\\media\\image.png'。当我查看数据库时,profile_image 字段被填充为“image.png”,但该文件没有出现在项目的任何文件夹中。

settings.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/'

urls.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">

【问题讨论】:

  • 你是否加入了enctype='multipart/form-data?
  • 不,那去哪儿了?在输入表单中?我试试看
  • 是的,当您使用具有文件上传控件的表单时,您需要包含此内容,否则将无法正常工作
  • 是的,就是这样,谢谢!

标签: python django


【解决方案1】:

使用&lt;form enctype='multipart/form-data' action='action-url' &gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 2016-02-15
    • 2012-04-07
    • 2017-03-04
    • 2021-03-29
    相关资源
    最近更新 更多