[英]How can I display pictures saved in a database?
This is my models file.这是我的模型文件。 I tried checking if there's a method for displaying class objects as a non-string.... Is there anything like that?我尝试检查是否有将类对象显示为非字符串的方法....有类似的东西吗?
class Images(models.Model):
# height = models.PositiveIntegerField()
# width=models.PositiveIntegerField()
file=models.ImageField(upload_to='images/')
#height_field='height', width_field = 'width
# file = models.ImageField(#upload_to=user_directory_path,
# width_field=100, height_field=100, blank=True, null=True)
name = models.CharField(max_length=30)
description = models.TextField(help_text="Give a short description of the image", max_length=100)
def __str__(self):
return self.name
This the html file这是html文件
h1>This is the House Page</h1>
{%for pic in pic%}
{{pic}}
{% comment %} <img src="{{pic}}" alt=""> {% endcomment %}
{%endfor%}
This is the view for the above html page这是上面 html 页面的视图
def House(request):
pic = Images.objects.all()
return render(request, 'house.html', {'pic': pic})
This is the form that saves the picture这是保存图片的表格
<h1>Upload Your Image Here</h1>
<form action="" method="POST" enctype="multipart/form-data"> <!--To allow images-->
{% csrf_token %}
{{form.as_p}}
<br><br>
<input type="submit" value="Submit">
</form>
And this is the view for the above html page这是上面 html 页面的视图
def imgUpload(request):
form = ImageForm
if request.method == 'POST':
file = request.POST['file']
name = request.POST['name']
description = request.POST['description']
form = ImageForm(request.POST, request.FILES)
pic = Images.objects.create(file=file, name=name, description=description)
pic.save()
return render(request, 'house.html', {'pic': pic})
#return HttpResponseRedirect('/fileupload.html?submitted=True')
else:
return render(request, 'fileupload.html',{'form': form})
Add to your model property get_img_url:添加到您的模型属性 get_img_url:
class Images(models.Model):
# height = models.PositiveIntegerField()
# width=models.PositiveIntegerField()
file=models.ImageField(upload_to='images/')
#height_field='height', width_field = 'width
# file = models.ImageField(#upload_to=user_directory_path,
# width_field=100, height_field=100, blank=True, null=True)
name = models.CharField(max_length=30)
description = models.TextField(help_text="Give a short description of the image", max_length=100)
def __str__(self):
return self.name
@property
def get_img_url(self):
if self.file and hasattr(self.file, 'url'):
return self.file.url
else:
return ''
then in template:然后在模板中:
h1>This is the House Page</h1>
{%for pic in pic%}
{{pic}}
{% comment %} <img src="{{pic.get_img_url}}" alt=""> {% endcomment %}
{%endfor%}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.