Advertisement
johnmahugu

web2py - Quick List/Update/Create table snippe

Aug 14th, 2015
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1.  
  2.  
  3. Quick List/Update/Create table snippet
  4. Recipe by Benigno Calvo (benigno) on 2009-12-09 in Controller
  5. Views (841)Favorite (0)Like (0)Dislike (0)Subscribe (0)
  6.  
  7. I do not particularly like having a function for each of the standard operations (select, update, create) on a single table. Moreso when I am prototyping or just want quick cruds. Not only do they clutter the controller a lot but they also end up being nasty URIs. So here is a little piece of very basic code, that I find myself reusing again and again. I hope it is useful for you too.
  8.  
  9. Share
  10. Quick Table Management Snippet
  11.  
  12. Just a little snippet that I find myself using again and again, to quickly create navigation to List, update and create tables:
  13.  
  14. In your controller:
  15.  
  16. def mylink(field, type, ref):
  17. """
  18. Returns a URL to link to in crud.selects.
  19. """
  20. return URL(r=request, args=[field])
  21.  
  22. def table_name():
  23. """
  24. Maintain all the table_name records in the application
  25. Manage, list, create and update projects.
  26. """
  27. # SELECT if no args
  28. if len(request.args)<1:
  29. return dict(form=crud.select(db.table_name,linkto=mylink))
  30. # If 1 arg and it is 'create' then CREATE
  31. elif len(request.args)==1 and request.args[0]=='create':
  32. return dict(form=crud.create(db.table_name,next=URL(request.application,request.controller,'table_name')))
  33. # If 1 arg and its integer, EDIT it.
  34. elif len(request.args)==1:
  35. try:
  36. i=int(request.args[0])
  37. except:
  38. redirect(URL(r=request,f='index'))
  39. return dict(form=crud.update(db.table_name,i,next=URL(request.application,request.controller,'table_name')))
  40. else:
  41. redirect(URL(r=request,f='index'))
  42.  
  43. This leaves the following URLs for your table_name actions:
  44.  
  45. /appname/controller/table_name will display a SELECT of the table.
  46. /appname/controller/table_name/create will CREATE a new record for the table.
  47. /appname/controller/table_name/edit/ID will EDIT table_name.id == ID
  48.  
  49. Closing up
  50.  
  51. I really hope that this little snippet saves some of your time for quickly prototyping apps.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement