Reputation: 3100
I have an ImageField on a Profile model so users can upload images. However, when I try to upload an image I get this error: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\name\\Documents\\Projects\\project\\media\\image.png'
. When I look in the database, the profile_image field gets popuated as "image.png" but the file doesn't appear in any folders in the project.
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', ...]
template
<label for="profile_image">Profile Image (size cannot exceed 1 MB)</label></p>
<input id="profile_image" type="file" class="" name="profile_image">
Upvotes: 0
Views: 970
Reputation: 1047
Use <form enctype='multipart/form-data' action='action-url' >
Upvotes: 1