Commits

Atsushi Odagiri  committed b5208e9

add deleting row.

  • Participants
  • Parent commits 4640228

Comments (0)

Files changed (1)

File src/alchemyadmin/__init__.py

 from werkzeug.routing import Map, Rule
 from werkzeug.exceptions import HTTPException
 from werkzeug import Local, LocalManager
+from werkzeug import redirect
 from jinja2 import Environment, PackageLoader
 from sqlalchemy.orm import sessionmaker, scoped_session, class_mapper
 from formalchemy import Grid, FieldSet, Field
                    method='GET',
                    values=values)
 
+def make_delete_url(instance):
+    values = {}
+    for pk in class_mapper(instance.__class__).primary_key:
+        values[pk.name] = getattr(instance, pk.name)
+
+    return url_for('model_delete',
+                   method='POST',
+                   values=values)
+
 class Application(object):
     def __init__(self, settings, *models, **modelsdict):
         self.template_env = default_template_env
                           endpoint='model_update',
                           methods=['POST'], 
                           defaults={'model':m}))
+            delete_url = '/' + m + '/' + self.pk_url_map(self.models[m]) + ';delete'
+            urls.add(Rule(delete_url,
+                          endpoint='model_delete',
+                          methods=['POST'], 
+                          defaults={'model':m}))
 
             self.grids[m] = grid = Grid(self.models[m])
             grid.configure(readonly=True, pk=True)
             grid.append(Field('edit', 
-                              value=lambda item: '<a href="%s">Edit</a>' % make_edit_url(item)))
+                              value=lambda item: '<form action="%s"><button type="submit">Edit</button></form>' % make_edit_url(item)))
+            grid.append(Field('delete', 
+                              value=lambda item: '<form action="%s" method="post"><button type="submit">Delete</button></form>' % make_delete_url(item)))
             self.fieldsets[m] = fieldset = FieldSet(self.models[m],
                                                     session=self.DBSession)
         self.urls = urls
                        content_type='text/html;charset=utf-8')
         return res
 
+    def model_delete(self, request, model, **keys):
+        q = self.DBSession.query(self.models[model])
+        mapper = class_mapper(self.models[model])
+
+        for p in mapper.primary_key:
+            q = q.filter(p==keys[p.name])
+        row = q.one()
+        self.DBSession.delete(row)
+        self.DBSession.commit()
+        url = url_for('model_index', method='GET',
+                      values={'model':model})
+        return redirect(url)
+
+
     def model_create(self, request, model, **keys):
         row = self.models[model]()
         fs = self.fieldsets[model].bind(row, data=request.form)