Python 上传的图像未在Django中保存和显示
我正在制作用户档案,用户可以上传jpg图片作为他们的档案图片。但上传的图像既没有存储在我的媒体目录中,也没有显示在服务器上。它会继续显示“默认照片”。我已经在我的设置文件中设置了MEDIA_ROOT和MEDIA_URL,并且已经添加到了URL文件中,但仍然不起作用。我是Django的新手,如有任何帮助,将不胜感激 这是我的模型.py:Python 上传的图像未在Django中保存和显示,python,django,python-3.x,django-views,Python,Django,Python 3.x,Django Views,我正在制作用户档案,用户可以上传jpg图片作为他们的档案图片。但上传的图像既没有存储在我的媒体目录中,也没有显示在服务器上。它会继续显示“默认照片”。我已经在我的设置文件中设置了MEDIA_ROOT和MEDIA_URL,并且已经添加到了URL文件中,但仍然不起作用。我是Django的新手,如有任何帮助,将不胜感激 这是我的模型.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.C
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self):
super().save()
image=Image.open(self.image.path)
if image.height >300 or image.width > 300:
output_size=(300,300)
image.thumbnail(output_size)
image.save(self.image.path)
views.py:
def profile(request):
if request.method=='POST':
update_form=UserUpdateForm(request.POST, instance=request.user)
profile_form=ProfileUpdateForm(request.POST, request.FILES ,instance=request.user)
if update_form .is_valid() and profile_form.is_valid():
update_form.save()
profile_form.save()
messages.success(request, f'Your account has been updated!!')
return redirect('profile')
else:
update_form=UserUpdateForm(instance=request.user)
profile_form=ProfileUpdateForm(instance=request.user)
context={
'update_form': update_form,
'profile_form':profile_form,
}
return render(request, 'users/profile.html', context)
profile.html:
<div class="card" id="profile" style="width: 18rem;">
<img class="card-img-top" src="{{ user.profile.image.url }}" alt="Default photo">
<div class="card-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4"><h1>Profile Info</h1></legend>
{{ update_form|crispy }}
{{ profile_form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-oultline-info" type="submit"> Update </button>
</div>
</form>
</div>
在模型中创建图像字段
class Profile(models.Model):
image = models.ImageField(upload_to='account_image/', blank=True, null=True)
通过请求“获取”数据
def profile(request):
data = Profile.objects.filter(user=request.user)
return render(request, 'accounts/profile.html', locals())
在html中加载
<img class="img-responsive img-rounded" src="/media/{{user.profile.image}}">
显示媒体的设置
@ZarakiKenpachi将其添加到项目树中的postwhere is you MEDIA文件夹?@ZarakiKenpachi位于项目目录下,同时显示目录树的db和manage.pyshow映像。试试我的答案
<img class="img-responsive img-rounded" src="/media/{{user.profile.image}}">