1

我想知道如何在我的表单中添加删除按钮以删除图像。

该项目是一个简单的“图片查看器”,索引显示了所有存储的图像,但我想添加一个“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&aacute;genes</h2>
<ul>
{% for image in images_list %}
    <li>
        <img src="/{{ image.image }}" height="75" />
    </li>
{% endfor %}

</ul>

我想在 index.html 上添加删除图像的删除按钮:D

4

2 回答 2

1

网址.py

[.........]
url(
   r'^delete-image/(?P<id>\d+)/$', 
   'delete_image', 
   name="delete_image"
),
[.........]

视图.py

def delete_image(request, id):
    image = Image.objects.get(pk=id).delete()
    return HttpResponseRedirect(reverse('app_name:url_name'))

模板

<ul>
    {% for image in images_list %}
    <li>
        <img src="/{{ image.image }}" height="75" /> 
        <a href="{% url app_name:delete_image image.id %}">Delete</a>
    </li>
    {% endfor %}
</ul>
于 2013-04-05T02:50:47.237 回答
0

视图.py

from django.views.generic.edit import DeleteView
from django.core.urlresolvers import reverse_lazy
from myapp.models import Image

class ImageDelete(DeleteView):
    model = Image
    success_url = reverse_lazy('index')

网址.py

from myapp.views import index, ImageDelete

...
url(r'^image/(?P<id>\d+)/delete/$', ImageDelete.as_view(), name="image-delete"),
...

索引.html

{% for image in images_list %}
    <li>
        <img src="/{{ image.image }}" height="75" />
        <a href="{% url 'myapp:image-delete' image.id %}">Delete</a>
    </li>
{% endfor %}
于 2013-04-05T03:12:05.337 回答