Zine

open source content publishing system


Ticket #215: before-comment-created-2.patch

File before-comment-created-2.patch, 2.3 kB (added by arteme, 9 months ago)

A better patch that allows a plugin to signal that the form is invalid without providing an error message.

  • zine/forms.py

    diff --git a/zine/forms.py b/zine/forms.py
    a b  
    1010""" 
    1111from copy import copy 
    1212from datetime import datetime 
     13from itertools import chain 
    1314import os 
    1415 
    1516from zine.i18n import _, lazy_gettext, list_languages 
     
    155156        is not a post req or the form is invalid the return value is None, 
    156157        otherwise a redirect response to the new comment. 
    157158        """ 
    158         if req.method != 'POST' or not self.validate(req.form): 
     159        if req.method != 'POST': 
     160            return 
     161 
     162        valid = self.validate(req.form) 
     163        errors = emit_event('before-comment-created', req) 
     164 
     165        # event handler returns 'True' to signal field-specific error 
     166        field_errors = filter(lambda x: isinstance(x, bool) and x, errors) 
     167        valid = valid and (len(field_errors) == 0) 
     168 
     169        # event handler returns a list or a tuple of error string to 
     170        # signal form-wide errors 
     171        errors = filter(lambda x: not isinstance(x, bool) and \ 
     172                                  x is not None, errors) 
     173        errors = list(chain(*errors)) 
     174 
     175        if len(errors) > 0: 
     176            # update the form-wide error list with those added by the 
     177            # event handlers 
     178            error_list = self.errors.get(None, forms.ErrorList()) 
     179            error_list.extend(errors) 
     180            self.errors[None] = error_list 
     181            return 
     182 
     183        if not valid: 
    159184            return 
    160185 
    161186        # if we don't have errors let's save it and emit an 
  • zine/views/blog.py

    diff --git a/zine/views/blog.py b/zine/views/blog.py
    a b  
    238238        `before-comment-created`: 
    239239            this event is sent with the form as event data. Can return 
    240240            a list of error messages to prevent the user from posting 
    241             that comment. 
     241            that comment. Returning `True` will also prevent the comment 
     242            from being posted, but will not display as a form-wide error. 
     243            This is useful, for example, for plugins that inject a field 
     244            to the "new comment" form and will display a validation error 
     245            message along with that field. 
    242246 
    243247        `before-comment-saved`: 
    244248            executed right before the comment is saved to the database.