Как отобразить изображения, сохраненные в базе данных?
Это мой файл моделей. Я попытался проверить, есть ли метод отображения объектов класса в виде нестроки..... Есть ли что-нибудь подобное?
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
Это html-файл
h1>This is the House Page</h1>
{%for pic in pic%}
{{pic}}
{% comment %} <img src="{{pic}}" alt=""> {% endcomment %}
{%endfor%}
Это представление для приведенной выше html-страницы
def House(request):
pic = Images.objects.all()
return render(request, 'house.html', {'pic': pic})
Это форма, которая сохраняет изображение
<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>
А это вид для вышеуказанной 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})
Добавьте к вашей модели свойство 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%}