2017年10月18日 星期三

[Django] Queries - Remove

 Python   Django   Queries   Remove from database   


Introduction


We will add the delete function for removing item in product list page.

Environment


Python 3.6.2
Django 1.8.18     



Implement


Expected result



Url Pattern

urls.py

from app.views import home, productList, productCreate, productEdit, productRemove

urlpatterns = [
    url(r'^$', home, name='home'),
    url(r'^product/(?P<prodtype>\w+)/$', productList, name='productList'),
    url(r'^product/create$', productCreate, name='productCreate'),
    url(r'^product/edit/(?P<prodId>\w+)$', productEdit, name='productEdit'),
    url(r'^product/remove$', productRemove, name='productRemove'),
    url(r'^admin/', admin.site.urls),
]





Template

product-list.html

Add the <form> tag, submit button and hidden input for post back Product’s Id to view.  

{% for prod in Prods %}
        <tr>
            <td>{{ prod.Id }}</td>
            <td>{{ prod.Title }}</td>
            <td>{{ prod.Price }}</td>
            <td>
              <form action="{% url 'productRemove' %}" method="post">{% csrf_token %}
                <input type="hidden" name="Id" value="{{ prod.Id }}" />
                <input type="button" class="btn btn-success" value="Edit" onclick="location.href='{% url 'productEdit' prodId=prod.Id %}'" />
                <input type="submit" class="btn btn-warning" value="Remove" />               
              </form>
            </td>
        </tr>
{% endfor %}



View

It’s simple on the view, all we have to do is get the Product’s Id from request.Post(which returns QueryDict) by using request.Post.Get.

views.py

from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from app.models import Product
from share.enum import ProductTypeEnum

#region Product: Remove
def productRemove(request):

    prodtypeEnum = ProductTypeEnum.book # Default

    if request.method == 'POST':
        prodId = request.POST.get("Id", 0)
        entity = Product.objects.filter(Id=prodId).first()
        if entity is not None:
            prodtypeEnum = ProductTypeEnum[entity.ProdType.Name.lower()]
            entity.delete()
    else:
        pass
      
    return HttpResponseRedirect(reverse('productList', args=[prodtypeEnum.name.lower()]))
#endregion




Demo



Database: before deleting item





Delete something



Database: after deleting item


Github

沒有留言:

張貼留言