我想知道如何在我的表单中添加删除按钮以删除图像。
该项目是一个简单的“图片查看器”,索引显示了所有存储的图像,但我想添加一个“x”图标来删除该特定图像。
这是我的代码。
视图.py
from django.shortcuts import render, redirect
from gallery.forms import ImageForm
from gallery.models import Image
def index(request, image_form=None):
image_form = image_form or ImageForm(request.POST, request.FILES)
if request.method == 'POST':
if image_form.is_valid():
new_image = Image(image=request.FILES['image_file'])
new_image.save()
# obtenemos el listado de imagenes registradas
images_list = Image.objects.all().order_by('-id')
return render(request, 'index.html', {
'image_form' : image_form,
'images_list' : images_list,
})
模型.py
from django.db import models
from django.contrib import admin
class Image(models.Model):
image = models.FileField(upload_to='static/gallery/%Y/%m/%d')
admin.site.register(Image)
表格.py
from django import forms
class ImageForm(forms.Form):
image_file = forms.FileField(
label='choose a file',
help_text = 'Max 2 megabytes'
)
index.html(它显示图像列表)
<style>
ul {list-style:none; width:800px;}
ul li {float:left; margin:6px;}
</style>
<form action="./gallery" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p> {{ image_form.non_field_errors }} </p>
<p> {{ image_form.image_file.label_tag }} </p>
<p> {{ image_form.image_file.help_text }} </p>
<p>
{{ image_form.image_file.errors }}
{{ image_form.image_file }}
</p>
<p> <input type="submit" value="subir"> </p>
</form>
<h2>Imágenes</h2>
<ul>
{% for image in images_list %}
<li>
<img src="/{{ image.image }}" height="75" />
</li>
{% endfor %}
</ul>
我想在 index.html 上添加删除图像的删除按钮:D