python - how to delete an image using django? -


i want know how add delete button in form deleting image.

the project simple "pics viewer", index shows images stored want add "x" icon deleting specific image.

here code.

views.py

from django.shortcuts import render, redirect gallery.forms import imageform 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,        }) 

models.py

from django.db import models django.contrib import admin  class image(models.model):     image = models.filefield(upload_to='static/gallery/%y/%m/%d')  admin.site.register(image) 

forms.py

from django import forms  class imageform(forms.form):     image_file = forms.filefield(         label='choose file',         help_text = 'max 2 megabytes'     ) 

index.html (it shows list of images )

<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> {% image in images_list %}     <li>         <img src="/{{ image.image }}" height="75" />     </li> {% endfor %}  </ul> 

i want add on index.html delete button deleting image :d

urls.py

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

views.py

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

template

<ul>     {% 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> 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -