Commits

Chris Perkins committed 08de6b9

sprox form demo stuff

Comments (0)

Files changed (11)

moviedemo/controllers/sproxdemo.py

 from tg.controllers import RestController, redirect
 from moviedemo.model import DBSession, Movie, Genre, Director
 
+
 from sprox.dojo.tablebase import DojoTableBase as TableBase
 from sprox.dojo.fillerbase import DojoTableFiller as TableFiller
 
                          }
     __url__ = "/movies.json"
     
+    
 movie_table = MovieTable(DBSession)
 
 #uncomment this if you want to play with the "normal" table code
 
 #movie_table = MovieTable(DBSession);
 
+from sprox.formbase import AddRecordForm
+from sprox.widgets import PropertySingleSelectField
+
+class GenreField(PropertySingleSelectField):
+    def _my_update_params(self, d, nullable=False):
+        genres = DBSession.query(Genre).all()
+        options = [(genre.genre_id, '%s (%s)'%(genre.name, genre.description))
+                            for genre in genres]
+        d['options']= options
+        return d
+
+class NewMovieForm(AddRecordForm):
+    __model__ = Movie
+    __omit_fields__ = ['movie_id', 'genre_id']
+    __field_attrs__ = {'description':{'rows':'2'}}
+    __field_order__ = ['title', 'description', 'genre', 'directors']
+    __dropdown_field_names__ = {'genre':'description', 'directors':'name'}
+    genre = GenreField
+
+from tw.forms.fields import PasswordField
+
+
+from sprox.dojo.formbase import DojoAddRecordForm
+class NewMovieForm(AddRecordForm):
+    __model__ = Movie
+    __omit_fields__ = ['movie_id', 'genre_id']
+
+new_movie_form = NewMovieForm(DBSession)
+
 class SproxMovieController(RestController):
 
     @expose('moviedemo.templates.sproxdemo.movies.get_all')
 #        value = movie_filler.get_value()
 #        return dict(value=value)
 
+    @expose('moviedemo.templates.sproxdemo.movies.new')
+    def new(self, **kw):
+        tmpl_context.widget = new_movie_form.__widget__
+        return dict(values=kw)
+    
+    @validate(new_movie_form, error_handler=new)
+    @expose()
+    def post(self, **kw):
+        movie = Movie(**kw)
+        DBSession.add(movie)
+        flash('your movie was successfully added')
+        redirect('/movies/')
+
 class DirectorMovieTableFiller(TableFiller):
     __model__ = Movie
     __add_fields__ = {'related_movies':None}
     
 director_movie_table = DirectorMovieTable(DBSession);
 
+class SproxDirectorMovies(RestController):
+    @expose('json')
+    def get_all(self, **kw):
+        director_id = request.path.split('/')[2]
+        tmpl_context.widget = director_movie_table
+        director = DBSession.query(Director).get(director_id)
+        return director_movie_filler.get_value(director=director, **kw)
+
 class SproxDirectorController(RestController):
     
+    movies = SproxDirectorMovies()
+    
     @expose('moviedemo.templates.sproxdemo.directors.get_one')
     def get_one(self, director_id):
         tmpl_context.widget = director_movie_table
         director = DBSession.query(Director).get(director_id)
         value = director_movie_filler.get_value(director=director)
-        return dict(director=director, value=value)
+        return dict(director=director, value=value)
+    

moviedemo/model/__init__.py

     __tablename__ = "genres"
     genre_id = Column(Integer, primary_key=True)
     name = Column(String(100))
+    description = Column(String(200))
+
 
 class Movie(DeclarativeBase):
     __tablename__ = "movies"

moviedemo/model/auth.py

 
     group_id = Column(Integer, autoincrement=True, primary_key=True)
     group_name = Column(Unicode(16), unique=True, nullable=False)
+    description = Column(Unicode(255), unique=True, nullable=False)
     display_name = Column(Unicode(255))
     created = Column(DateTime, default=datetime.now)
     users = relation('User', secondary=user_group_table, backref='groups')

moviedemo/templates/sproxdemo/directors/get_one.html

     <div style="float:left width: 80%">
       <h1>${director.name}</h1>
       <h2 style="margin-top:1px;">Movies Directed</h2>
-      ${tmpl_context.widget(value=value)}
+      ${tmpl_context.widget(value=value, action=str(director.director_id)+'/movies.json')}
     </div>
   </div>
 </body>

moviedemo/templates/sproxdemo/directors/new.html

+<html xmlns="http://www.w3.org/1999/xhtml"
+      xmlns:py="http://genshi.edgewall.org/"
+      xmlns:xi="http://www.w3.org/2001/XInclude">
+  <xi:include href="master.html" />
+<head/>
+<body>
+  <div style="height:0px;"> &nbsp; </div>
+  <div>
+    <div style="float:left width: 80%">
+      <h2 style="margin-top:1px;>Create New Movie</h2>
+      ${tmpl_context.widget()}
+    </div>
+  </div>
+</body>
+</html>

moviedemo/templates/sproxdemo/movies/new.html

 <html xmlns="http://www.w3.org/1999/xhtml"
       xmlns:py="http://genshi.edgewall.org/"
       xmlns:xi="http://www.w3.org/2001/XInclude">
-
-<xi:include href="master.html" />
+  <xi:include href="master.html" />
 <head/>
 <body>
   <div style="height:0px;"> &nbsp; </div>
-  <h2> New Movie</h2>
-  <form method="POST" action="./">
-    <table>
-    <tr><td>Title </td><td><input type="textfield" name="title" value="${values.get('title', '')}"/>${tmpl_context.form_errors.get('title')}</td></tr>
-    <tr><td>Description</td><td> <textarea name="description">${values.get('description')}</textarea>${tmpl_context.form_errors.get('description')}</td></tr>
-    <tr><td>Genre</td>
-        <td>
-          <select name="genre_id">
-              <py:for each="genre in genres">
-                <py:if test="values.get('genre_id') == unicode(genre.genre_id)">
-                  <option value="$genre.genre_id" selected="selected">$genre.name</option>
-                </py:if>
-                <py:if test="values.get('genre_id')!= unicode(genre.genre_id)">
-                  <option value="$genre.genre_id">$genre.name</option>
-                </py:if>
-              </py:for>
-          </select>
-        </td></tr>
-    <tr><td>Directors</td>
-        <td>
-          <select multiple="true" name="directors">
-              <py:for each="director in directors">
-                $director.name
-                <py:if test="unicode(director.director_id) in values.get('directors', [])">
-                  <option value="$director.director_id" selected="selected">$director.name</option>
-                </py:if>
-                <py:if test="unicode(director.director_id) not in values.get('directors', [])">
-                  <option value="$director.director_id">$director.name</option>
-                </py:if>
-              </py:for>
-          </select>
-        </td></tr>
-    <tr><td>Release Date</td><td><input type="textfield" name="release_date" value="${values.get('release_date')}"/>${tmpl_context.form_errors.get('release_date')}</td></tr>
-    </table><br/>
-    <input type="submit" value="create"/>
-  </form>
-  
+  <div>
+    <div style="float:left width: 80%">
+      <h2 style="margin-top:1px;">Create New Movie</h2>
+      ${tmpl_context.widget(values=values, action='./')}
+    </div>
+  </div>
 </body>
 </html>

moviedemo/websetup.py

-"""Setup the moviedemo application"""
-import logging
-from datetime import datetime
-
-import transaction
-from tg import config
-
-from moviedemo.config.environment import load_environment
-
-log = logging.getLogger(__name__)
-
-def setup_app(command, conf, vars):
-    """Place any commands to setup moviedemo here"""
-    load_environment(conf.global_conf, conf.local_conf)
-    # Load the models
-    from moviedemo import model
-    print "Creating tables"
-    model.metadata.create_all(bind=config['pylons.app_globals'].sa_engine)
-
-    u = model.User()
-    u.user_name = u'manager'
-    u.display_name = u'Example manager'
-    u.email_address = u'manager@somedomain.com'
-    u.password = u'managepass'
-
-    model.DBSession.add(u)
-
-    g = model.Group()
-    g.group_name = u'managers'
-    g.display_name = u'Managers Group'
-
-    g.users.append(u)
-
-    model.DBSession.add(g)
-
-    p = model.Permission()
-    p.permission_name = u'manage'
-    p.description = u'This permission give an administrative right to the bearer'
-    p.groups.append(g)
-
-    model.DBSession.add(p)
-
-    u1 = model.User()
-    u1.user_name = u'editor'
-    u1.display_name = u'Example editor'
-    u1.email_address = u'editor@somedomain.com'
-    u1.password = u'editpass'
-    model.DBSession.add(u1)
-    
-    genres = ['action', 'animation', 'comedy', 'documentary', 'drama', 'sci-fi']
-
-    for genre in genres:
-        model.DBSession.add(model.Genre(name=genre))
-        
-    directors = ['Robert Zemeckis', 'David Fincher', 'Andy Wachowski', 'Larry Wachowski', 'Joel Coen']
-    
-    for i, director in enumerate(directors):
-        director = model.Director(name=director)
-        model.DBSession.add(director)
-        directors[i] = director
-    
-    movies = [
-        {'title': 'Back to the Future',
-         'description':"""In 1985, Doc Brown invents time travel; in 1955, Marty McFly accidentally prevents his parents from meeting, putting his own existence at stake""",
-         'genre_id': 6,
-         'release_date': '4/3/85',
-         'directors': [directors[0]],
-         },
-        {'title': 'Fight Club',
-         'description':"""An office employee and a soap salesman build a global organization to help vent male aggression.""",
-         'genre_id': 1,
-         'release_date': '10/14/99',
-        'directors': [directors[1]],
-         },
-        {'title': 'The Matrix',
-         'description':"""A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against the controllers of it.""",
-         'genre_id': 1,
-         'release_date': '3/31/99',
-         'directors': [directors[2], directors[3]],
-         },
-        {'title': 'The Big Lebowski',
-         'description':""""Dude" Lebowski, mistaken for a millionaire Lebowski, seeks restitution for his ruined rug and enlists his bowling buddies to help get it.""",
-         'genre_id': 3,
-         'release_date': '3/6/98',
-         'directors': [directors[4]]
-         },
-    ]
-    for movie in movies:
-        movie['release_date'] = datetime.strptime(movie['release_date'],'%m/%d/%y')
-        model.DBSession.add(model.Movie(**movie))
-            
-    model.DBSession.flush()
-
-    transaction.commit()
-    print "Successfully setup"

moviedemo/websetup/__init__.py

+# -*- coding: utf-8 -*-
+"""Setup the tgtest application"""
+
+import logging
+
+from moviedemo.config.environment import load_environment
+
+__all__ = ['setup_app']
+
+log = logging.getLogger(__name__)
+
+from schema import setup_schema
+from bootstrap import bootstrap
+
+def setup_app(command, conf, vars):
+    """Place any commands to setup tgtest here"""
+    load_environment(conf.global_conf, conf.local_conf)
+    setup_schema(command, conf, vars)
+    bootstrap(command, conf, vars)

moviedemo/websetup/bootstrap.py

+# -*- coding: utf-8 -*-
+"""Setup the tgtest application"""
+from datetime import datetime
+import logging
+from tg import config
+from moviedemo import model
+import transaction
+from bootalchemy.loader import YamlLoader
+
+def bootstrap(command, conf, vars):
+    """Place any commands to setup tgtest here"""
+
+    # <websetup.bootstrap.before.auth
+    from sqlalchemy.exc import IntegrityError
+    try:
+        from moviedemo import model
+        print "Adding Bootstrap Data..."
+        
+        data = """
+- Group:
+    - {'&managers': {group_name:  managers, display_name:  Managers Group, description:  This permission give an administrative right to the bearer}}
+  User:
+    - {'&manager': {user_name:  manager, display_name:  Example manager, email_address:  manager@somedomain.com, password: managepass, groups: ['*managers']}}
+    - {'&editor':  {user_name:  editor, display_name:  Example editor, email_address:  editor@somedomain.com, password: editorpass}}
+  flush:
+- Genre:
+    - {'&action': {name: action, description: 'car chases, sex and violence'}}
+    - {'&animation': {name: animation, description: cartoons and computer rendered flicks}}
+    - {'&comedy': {name: comedy, description: funny stuff}}
+    - {'&documentary': {name: documentary, description: purely information}}
+    - {'&drama': {name: drama, description: makes your girlfriend cry}}
+    - {'&sci_fi': {name: sci-fi, description: 'read: furturism'}}
+  Director:     
+    - {'&robert': {name: Robert Zemeckis}}
+    - {'&david' : {name: David Fincher}}
+    - {'&andy'  : {name: Andy Wachowski}}
+    - {'&larry' : {name: Larry Wachowski}}
+    - {'&joel'  : {name: Joel Coen}}
+  Movie:
+    - description: In 1985, Doc Brown invents time travel; in 1955, Marty McFly accidentally prevents his parents from meeting, putting his own existence at stake
+      title: Back to the Future
+      release_date:  1985-4-3
+      genre: "*sci_fi"
+      directors: ["*robert"]
+    - description: An office employee and a soap salesman build a global organization to help vent male aggression.
+      title: Fight Club
+      release_date:  1999-10-14
+      genre: "*action"
+      directors: ["*david"]
+    - description: A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against the controllers of it.
+      title: The Matrix
+      release_date:  1999-3-31
+      genre: "*sci_fi"
+      directors: ["*larry", "*andy"]
+    - description: '"Dude" Lebowski, mistaken for a millionaire Lebowski, seeks restitution for his ruined rug and enlists his bowling buddies to help get it.'
+      title: The Big Lebowski
+      release_date:  1998-3-6
+      genre: "*comedy"
+      directors: ["*joel"]
+  flush:
+"""
+        loader = YamlLoader(model)
+        loader.loads(model.DBSession, data)
+        transaction.commit()
+    except IntegrityError:
+        print 'Warning, there was a problem adding your auth data, it may have already been added:'
+        import traceback
+        print traceback.format_exc()
+        transaction.abort()
+        print 'Continuing with bootstrapping...'
+        
+
+    # <websetup.bootstrap.after.auth>

moviedemo/websetup/schema.py

+# -*- coding: utf-8 -*-
+"""Setup the tgtest application"""
+
+import logging
+import transaction
+from tg import config
+
+def setup_schema(command, conf, vars):
+    """Place any commands to setup tgtest here"""
+    # Load the models
+
+    # <websetup.websetup.schema.before.model.import>
+    from moviedemo import model
+    # <websetup.websetup.schema.after.model.import>
+
+    
+    # <websetup.websetup.schema.before.metadata.create_all>
+    print "Creating tables"
+    model.metadata.create_all(bind=config['pylons.app_globals'].sa_engine)
+    # <websetup.websetup.schema.after.metadata.create_all>
+    transaction.commit()
     from ez_setup import use_setuptools
     use_setuptools()
     from setuptools import setup, find_packages
+    
 
 setup(
     name='moviedemo',
     #url='',
     install_requires=[
         "TurboGears2",
-	"Catwalk",
+        "bootalchemy",
         "zope.sqlalchemy",
         "repoze.what-quickstart",
                 ],
     packages=find_packages(exclude=['ez_setup']),
     include_package_data=True,
     test_suite='nose.collector',
-    tests_require=['WebTest', 'BeautifulSoup'],
     package_data={'moviedemo': ['i18n/*/LC_MESSAGES/*.mo',
                                  'templates/*/*',
                                  'public/*/*']},