python - 显示上传的文件django

标签 python django

我的 Django 有问题。我需要在单页中显示我的文件

所以我创建模型:

class UserProfile(models.Model):
profile_img = models.ImageField(upload_to='media/images/', blank=True, null=True)
profile_text = models.TextField()
profile_title = models.CharField(max_length=300)
profile_user = models.ForeignKey(User)

和表格

class ProfileForm(ModelForm):
class Meta:
    model = UserProfile
    fields = ['profile_img', 'profile_title']

然后查看

def cabinet(request):
form = ProfileForm(request.POST, request.FILES or None)
if request.method == 'POST' and form.is_valid():
    obj = UserProfile(profile_img=request.FILES['profile_img'])
    obj = form.save(commit=False)
    obj.profile_user = request.user
    obj.save()
    return redirect(reverse(cabinet))
return render(request, 'cabinet.html', {'form': form})

我尝试使用 View

def user_page(request):
profile = UserProfile.objects.all()
return render(request, 'user_page.html', {'profile':profile})

{% for img in profile %}
{{ img.profile_img }}
{% endfor %}

这不工作 请帮助我,我尝试阅读文档,但没有帮助

最佳答案

因此,您粘贴的代码只会打印每个 profile.profile_img 的路径。 profile_img 属性也是如此,它只存储您上传的图像的路径,而不存储图像本身。为了使用上传到您网站的媒体文件,您需要在 settings.py 中指定 MEDIA_ROOTMEDIA_URL

然后您需要将其附加到您的urls.py中。您可能还想看看这里:show images in Django templates

完成此操作后,要在模板中显示图像,只需使用 HTML 标签

<img src="{{MEDIA_URL}}{{ img.profile_img }}" />

关于python - 显示上传的文件django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32033121/

相关文章:

Python - 在 Flask 中将查询结果从服务器返回到客户端

Python 碎片 : How to return nothing if xpath doesn't exist?

python - Django 模板标签显示对象的错误日期

python - Python中的关键字提取

python - 创建一个函数来为上传的图像位置指定目录

python - 以时间间隔对数据库进行调度过滤

django - 无法根据请求用户进行 autocomplete_light 过滤 taggit 标签

p4 diff 上的 Python 代码覆盖率

python - 开始使用 Spring Python 的最佳在线教程是什么

python - 在 ios 上的 kivy 应用程序中写入/保存文件的问题