Не получается получить изображение профиля из html-формы, но другие данные получаются
это модель профиля
class Profile(models.Model):
user=models.ForeignKey(User,on_delete=models.CASCADE)
id_user=models.IntegerField()
bio=models.TextField(blank=True)
profileimg=models.ImageField(upload_to='profile_images',default='defaultdp.png')
location=models.CharField(max_length=100,blank=True)
def __str__(self):
return self.user.username
это html-форма
<form action="" method="POST" enctype="multipart/form-data">
{%csrf_token%}
<div class="col-span-2">
<label for=""> Profile Picture</label>
<img height="100" width="100" src="{{user_profile.profileimg.url}}">
<input type="file" name="profileimg" placeholder="" class="shadow-none bg-gray-100">
</div>
<form>
это views.py
@login_required(login_url='signin')
def settings(request):
user_profile=Profile.objects.get(user=request.user)
if request.method == 'POST':
if request.FILES.get('image')==None:
image=user_profile.profileimg
bio=request.POST ['bio']
location=request.POST['location']
user_profile.profileimg=image
user_profile.bio=bio
user_profile.location=location
user_profile.save()
if request.FILES.get('image')!=None:
image=request.FILES.get('image')
bio=request.POST ['bio']
location=request.POST['location']
user_profile.profileimg=image
user_profile.bio=bio
user_profile.location=location
user_profile.save()
return redirect('settings')
return render(request,'setting.html',{'user_profile': user_profile})
Изображение профиля, которое я получаю, это defaultdp.png, которое является изображением по умолчанию, если не загружен файл. Я думаю, что файл, который я загружаю, не сохраняется в базе данных или я не знаю, что здесь происходит. Кто-нибудь может помочь мне разобраться с этим? Если я упустил какой-то фрагмент кода для отладки, пожалуйста, укажите его. Я отредактирую вопрос с указанным кодом.
Я бы дважды проверил конфигурацию static и media в файле settings.py из папки проекта.
MEDIA_ROOT = os.path.join(BASE_DIR, 'images/') # 'images' is my media folder in project folder.
MEDIA_URL = '/media/'
и добавьте следующее в urls.py из папки проекта.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
и теперь добавьте контекстный обработчик медиа в файл settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
#here add your context Processors
'django.template.context_processors.media',
],
},
},
]
Проверьте работу со статическими медиафайлами в здесь.