adding new art with user relations is there, sort of. Still needs adding relations... wtforms
authorNick Retallack <nickretallack@gmail.com>
Tue, 1 Dec 2009 09:15:02 +0000 (01:15 -0800)
committerNick Retallack <nickretallack@gmail.com>
Tue, 1 Dec 2009 09:15:02 +0000 (01:15 -0800)
floof/controllers/art.py
floof/controllers/relation.py
floof/model/users.py
floof/public/layout.css
floof/templates/art/new.mako

index bb3bc19..be75ee7 100644 (file)
@@ -14,6 +14,52 @@ from floof.model.comments import Discussion
 
 from sqlalchemy.exceptions import IntegrityError
 
+from wtforms.validators import ValidationError
+from wtforms import *
+
+
+class ArtUploadForm(Form):
+    by = TextField('Artists')
+    file = FileField('Upload')
+    url = TextField('Link')
+
+    # TODO: make this general purpose
+    def validate_file(self, field):
+        if field.data == u'':
+            raise ValidationError('File is required')
+    
+    # Also make this into a general User List field validator
+    """ PLEASE NOTE!  I just realized that I need to have a __str__ method on User
+    to get it to write the usernames back in the form when it redisplays them, since
+    this validator turns them into user objects instead.  This fact actually sounds dangerous
+    to me in the future, since it means I proably shouldn't be changing the data input
+    by the user right here in the validator, or the user will see the post-mangled data instead
+    of what they actually typed.  Hm.
+    
+    One solution to this could be to only look up the users after normal validation is over, 
+    and then manually add validation errors to the form if that fails.  But I think that kind of
+    sucks.  Perhaps the ideology in Formish, where they keep Validation and Conversion as
+    separate tasks, is a better way of doing it?  That way there is less risk of changing the user's
+    input -- you do that at the conversiot stage -- yet it is still encapsulated in the form workflow.
+    Hm.  But that means I'd have to query for the users in the validation step and throw them away,
+    or something equally stupid.  Guess there's no perfect solution here, but I thought it was
+    worth discussing.
+    
+    Btw, this is meant to be used by a field with multi user autocompletion on it (like on stackoverflow tags),
+    so the user should never actually submit anything invalid unless they disable javascript and force it.
+    """
+    def validate_by(self, field):
+        if not field.data:
+            raise ValidationError("Needs at least one creator")
+        user_names = field.data.split()
+        users = []
+        # TODO: Could totally do a filter__in here instead of picking them out individually
+        for user_name in user_names:
+            user = User.get_by(name=user_name)
+            if not user:
+                raise ValidationError("Couldn't find user %s" % user_name)
+            users.append(user)
+        field.data = users
 
 class ArtController(BaseController):
     def __before__(self, id=None):
@@ -24,34 +70,38 @@ class ArtController(BaseController):
 
     def new(self):
         """ New Art! """
+        c.form = ArtUploadForm()
         return render("/art/new.mako")
 
     # TODO: login required
     def create(self):
-        # if 'file' not in request.params or not request.params['file']:
-        #     return "Validation Error: Needs a File"
-
-
-        c.art = Art(uploader=c.user, **request.params)
-        c.art.discussion = Discussion(count=0)
-        
-
-        artist = User.get_by(name=request.params['artist'])
-        if not artist:
-            return "Validation Error: Artist not found"
-
-        relation = UserRelation(user=artist, kind="by", creator=c.user, art=c.art)
-
-        try:
-            elixir.session.commit()
-            redirect(url('show_art', id=c.art.id))
-        except IntegrityError:
-            # hurr, there must be a better way to do this but I am lazy right now
-            hash = c.art.hash
-            elixir.session.rollback()
-            duplicate_art = Art.get_by(hash=hash)
-            h.flash("We already have that one.")
-            redirect(url('show_art', id=duplicate_art.id))
+        c.form = ArtUploadForm(request.params)
+        if c.form.validate():
+
+            c.art = Art(uploader=c.user, **request.params)
+            c.art.discussion = Discussion(count=0)
+
+            for artist in c.form.by.data:
+                UserRelation(user=artist, kind="by", creator=c.user, art=c.art)
+
+            file = request.params['file']
+
+            try:
+                elixir.session.commit()
+                redirect(url('show_art', id=c.art.id))
+            except IntegrityError:
+                # hurr, there must be a better way to do this but I am lazy right now
+                hash = c.art.hash
+                elixir.session.rollback()
+                duplicate_art = Art.get_by(hash=hash)
+                h.flash("We already have that one.")
+                redirect(url('show_art', id=duplicate_art.id))
+
+        else:
+            ## TODO: JavaScript should be added to the upload form so that it is
+            ## impossible to submit the form when it contains any invalid users, 
+            ## so this never happens.  Only autocompled usernames should be allowed.
+            return render("/art/new.mako")
 
 
     def show(self, id):
index b1d415d..48e7a46 100644 (file)
@@ -11,6 +11,9 @@ from floof.model import Art, UserRelation
 from floof.model.users import User
 import elixir
 
+# TODO!!!  Implement adding a related user the same way that it works
+# on the "add new art" page
+
 class RelationController(BaseController):
     def create(self, art_id, kind):
         art = h.get_object_or_404(Art, id=art_id)
index c38197c..4f83a75 100644 (file)
@@ -20,6 +20,9 @@ class User(Entity):
 
     def __unicode__(self):
         return self.name
+    
+    def __str__(self):
+        return self.name
 
     def __init__(self, **kwargs):
         super(User, self).__init__(**kwargs)
index b175705..1fa629e 100644 (file)
@@ -23,6 +23,9 @@ dl.form { margin: 1em 0; padding-left: 1em; border-left: 0.5em solid gray; }
 dl.form dt { padding-bottom: 0.25em; font-style: italic; }
 dl.form dd { margin-bottom: 0.5em; }
 
+.errors {color:red;}
+
+
 /* Comments */
 .comment {}
 .comment .header { background: #d8d8d8; }
index 97cac9e..4204700 100644 (file)
@@ -3,8 +3,31 @@
 <h1>Add New Art</h1>
 <p>Now: Upload a file.  Later: Supply a link?  Not exclusive to uploading.</p>
 
+## Todo: write some macros to make outputting form fields easier.
+
 ${h.form(h.url('create_art'), multipart=True)}
-Artist: ${h.text('artist')}
-${h.file('file')}
+
+${normal_field(c.form.by)}
+${normal_field(c.form.file)}
+
+
+##Artist: ${h.text('artist')}
+##${h.file('file')}
 ${h.submit(None, 'Upload!')}
 ${h.end_form()}
+
+
+
+<%def name="normal_field(field)">
+<div>
+${field.label()|n}
+${field()|n} 
+%if field.errors:
+<ul class="errors">
+%for error in field.errors:
+<li>${error}
+%endfor
+</ul>
+%endif
+</div>
+</%def>