settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
型号.py
class Profile(models.Model):
img=models.ImageField(upload_to='media',null=True)
bio=models.TextField(max_length=50, null=True)
user=models.OneToOneField(User,related_name='profile',on_delete=models.CASCADE)
urls.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
所以基本上,在我上传图像后,没有创建媒体文件夹,我正在开发最新版本的django,如果需要提供更多信息,请告知。
编辑:我按照别人的建议创建了一个媒体文件夹,但图像没有显示,也不在我创建的的媒体文件夹内
<html>
<body>
<img src="{{ user.profile.img.url }}" alt="{{profile.user}}">
<br>
<br>
{{profile.user}}
</body>
</html>
这是用于显示图像的代码
开发人员工具控制台中html的输出为:
<html>
<body>
<img src="" alt="somename">
<br>
<br>
somename
</body>
</html>
负责上传图像的html代码:
<html>
<form method='post' enctype="multipart/form-data">
{% csrf_token %}
<input type="file" id="img" name="img" accept="image/*">
<textarea name='bio' placeholder='Write about yourself'></textarea>
<input type="submit">
</form>
</html>
views.py
#this function responsible for uploading image
def user_profile_view(request,pk):
user=User.objects.first()
if request.method == 'POST':
img=request.POST.get('img')
bio=request.POST.get('bio')
profile=Profile.objects.create(img=img,bio=bio,user=user)
return render(request,'profile.html')
#this function responsible for displaying profile.
def user_profile_display(request,pk):
user=get_object_or_404(User,pk=pk)
profile=Profile.objects.get(user=user)
return render(request,'display_profile.html',{'profile':profile})
您应该自己创建媒体目录。
mkdir media
echo media >> .gitignore # use this command to make the git ignore all the media files
echo media >> media/README.md
git add -f media/README.md # use this command to make sure that
# when you use the project in other host,
# the media directory will be created automatically
检查您是否正确接收到views.py、中的图像
使用request.files获取img。请检查媒体文件夹是否在您的基本目录中,并且子文件夹(如果有(的名称是否正确。
views.py:
if request.method == "POST":
answer_form = Answer_form(data=request.POST)
if(answer_form.is_valid()):
ans = answer_form.save(commit=False)
#ans.user = user
if 'img' in request.FILES:
ans.img = request.FILES['img']
ans.save()
else:
print(answer_form.errors)
这是文档页面:
文件上传
假设您的设置在设置中,并且您的图像已经成功上传(否则您需要检查路径和文件夹权限设置(
MEDIA_DIR = f'{BASE_DIR}/media'
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
然后你应该这样使用:
<img src="/media/{{ user.profile.img}}" alt="{{profile.user}}">