A form factory for a given model badges
424939
def badge_form(model):
    ''''''
    class BadgeForm(ModelForm):
        model_class = Badge

        kind = fields.RadioField(
            _('Kind'), [validators.DataRequired()],
            choices=model.__badges__.items(),
            description=_('Kind of badge (certified, etc)'))

    return BadgeForm
1287671
def bootstrap_form_for(record_or_name_or_array, *args, &proc)
      options = args.extract_options!
      options[:html] ||= {}

      # :horizontal
      if horizontal = options.delete(:horizontal)
        # set the form html class for horizontal bootstrap forms
        options[:html][:class] ||= ''
        options[:html][:class] = (options[:html][:class].split(' ') << 'form-horizontal').uniq.join(' ')
      end

      # We switch autocomplete off by default
      raise 'autocomplete should be defined an html option' if options[:autocomplete]
      options[:html][:autocomplete] ||= 'off'

      form_for(record_or_name_or_array, *(args << options.merge(builder: NdrUi::BootstrapBuilder))) do |form|
        # Put the form builder into horizontal mode (if necessary)
        form.horizontal_mode = horizontal if horizontal

        # yield to the provided form block
        yield(form)
      end
    end
137794
def get_form(self, request, obj=None, **kwargs):
        
        widgets = kwargs.pop('widgets', {})
        labels = kwargs.pop('labels', {})
        glossary_fields = kwargs.pop('glossary_fields', self.glossary_fields)
        widgets.update(glossary=JSONMultiWidget(glossary_fields))
        labels.update(glossary='')  # remove label for glossary, since each subfields provides a label itself
        kwargs.update(widgets=widgets, labels=labels)
        form = super(CascadePluginBase, self).get_form(request, obj, **kwargs)
        # help_text can not be cleared using an empty string in modelform_factory
        form.base_fields['glossary'].help_text = ''
        if request.method == 'POST':
            is_shared = bool(request.POST.get('shared_glossary'))
            for field in glossary_fields:
                if not (is_shared and field.name in self.sharable_fields):
                    form.base_fields['glossary'].validators.append(field.run_validators)
        form.glossary_fields = glossary_fields
        return form
400038
def get_form_kwargs(self):
        
        kwargs = super(ModelFormMixin, self).get_form_kwargs()
        kwargs['poll'] = self.object
        return kwargs
711843
def make_localised_form(model, form, exclude=None):
    
    
    newfields = {}  
    
    for localized_field in model.localized_fields:
        # get the descriptor, which contains the form field
        default_field_descriptor = getattr(model, localized_field)
        
        # See if we've got overridden fields in a custom form.
        if hasattr(form, 'declared_fields'):
            form_field = form.declared_fields.get(
                localized_field, default_field_descriptor.form_field)
        else:
            form_field = default_field_descriptor.form_field
         
        # wrap the widget to show the origin of the value;
        # either database, catalog or fallback.
        if type(form_field.widget) is not WidgetWrapper:
            form_field.widget = WidgetWrapper(form_field.widget)
         
        newfields[localized_field] = form_field
 
    if hasattr(form, 'Meta'):
         setattr(form.Meta, 'model', model)
    else:
         newfields['Meta'] = type('Meta', tuple(), {'model':model})
    
    newfields['localized_fields'] = model.localized_fields
    
    return ModelFormMetaclass(model.__name__, (LocalisedForm, form), newfields)
1241679
def thread_helper(form_tag=True, edit_mode=False, for_moderator=False):
    
    helper = FormHelper()
    helper.form_action = '.'
    helper.attrs = {'data_abide': ''}
    helper.form_tag = form_tag
    
    fieldsets = [
        Row(
            Column(
                'subject',
                css_class='small-12'
            ),
        ),
    ]
    
    # Category field only in edit form
    if edit_mode:
        fieldsets.append(
            Row(
                Column(
                    'category',
                    css_class='small-12'
                ),
            ),
        )
    
    if for_moderator:
        fieldsets.append(
            Row(
                Column(
                    'sticky',
                    css_class='small-12 medium-4'
                ),
                Column(
                    'announce',
                    css_class='small-12 medium-4'
                ),
                Column(
                    'closed',
                    css_class='small-12 medium-4'
                ),
            ),
        )
    
    # First message is not in edit form
    if not edit_mode:
        fieldsets.append(
            Row(
                Column(
                    'text',
                    css_class='small-12'
                ),
            ),
        )
    
    if for_moderator:
        fieldsets.append(
            Row(
                Column(
                    'visible',
                    css_class='small-12'
                ),
            ),
        )
    
    # Threadwatch option is not in edit form
    if not edit_mode:
        fieldsets.append(
            Row(
                Column(
                    'threadwatch',
                    css_class='small-12'
                ),
            ),
        )
    
    fieldsets = fieldsets+[
        ButtonHolderPanel(
            Submit('submit', _('Submit')),
            css_class='text-right',
        ),
    ]
    
    helper.layout = Layout(*fieldsets)
    
    return helper
1373579
def right_model_factory(*, validator=validators.is_right_model,
                        ld_type='Right', **kwargs):
    
    return _model_factory(validator=validator, ld_type=ld_type, **kwargs)
280189
def get_form(self, form_class):
        """"""
        kwargs = self.kwargs
        kwargs.update(self.get_form_kwargs())
        kwargs.update({
            'request': self.request,
            'next_view': WidgetCreateView
        })
        return form_class(**kwargs)
112199
def _get_forms(profile, instance, request, undo=False, prefix=""):
    
    anonymous = profile is None and request.user.username == ANONYMOUS_USERNAME

    if not profile and not anonymous:
        return []

    if prefix:
        prefix += "-{}".format(instance.pk)
    else:
        prefix = "{}".format(instance.pk)

    kwargs = dict(
        initial={"pk": instance.pk},
        profile=profile,
        prefix=prefix,
        undo=undo,
    )

    ret = []
    if (not instance.closed or undo) and instance.workshifter:
        workshifter = instance.workshifter or instance.liable
        pool = instance.pool

        if not profile:
            managers = []
        else:
            managers = Manager.objects.filter(incumbent__user=profile.user)

        verify, blow = False, False

        # The many ways a person can be eligible to verify a shift...
        if instance.verify == AUTO_VERIFY:
            pass
        elif instance.verify == SELF_VERIFY:
            verify = True
        elif instance.verify == OTHER_VERIFY and profile != workshifter:
            verify = True
        elif instance.verify == ANY_MANAGER_VERIFY and managers:
            verify = True
        elif instance.verify == POOL_MANAGER_VERIFY and \
          set(managers).intersections(pool.managers):
            verify = True
        elif instance.verify == WORKSHIFT_MANAGER_VERIFY and \
          any(i.workshift_manager for i in managers):
            verify = True

        if verify and not instance.verifier:
            # Verify Shift
            action = "{}-{}".format(VerifyShiftForm.action_name, instance.pk)
            ret.append(
                VerifyShiftForm(
                    data=request.POST if action in request.POST else None,
                    **kwargs
                )
            )

        if pool.any_blown:
            blow = True

        if profile:
            pool_managers = pool.managers.filter(incumbent__user=profile.user)
            if pool_managers.count():
                blow = True

        if blow and not instance.blown:
            # Blown Shift
            action = "{}-{}".format(BlownShiftForm.action_name, instance.pk)
            ret.append(
                BlownShiftForm(
                    data=request.POST if action in request.POST else None,
                    **kwargs
                )
            )

    if profile is not None:
        marked_blown = UndoShiftForm.check_marked_blown(instance, profile)

        if marked_blown or instance.verifier == profile:
            # Undo Verify Shift
            action = "{}-{}".format(UndoShiftForm.action_name, instance.pk)
            ret.append(
                UndoShiftForm(
                    data=request.POST if action in request.POST else None,
                    **kwargs
                )
            )

    if not instance.closed:
        if not instance.workshifter:
            # Sign In
            action = "{}-{}".format(SignInForm.action_name, instance.pk)
            ret.append(
                SignInForm(
                    data=request.POST if action in request.POST else None,
                    **kwargs
                )
            )
        liable = instance.workshifter or instance.liable
        if (undo and liable is not None) or \
           instance.workshifter == profile:
            # Sign Out
            action = "{}-{}".format(SignOutForm.action_name, instance.pk)
            ret.append(
                SignOutForm(
                    data=request.POST if action in request.POST else None,
                    **kwargs
                )
            )

    return ret
1118008
def get_form_schema(form):
    """"""
    schema = {
        'type': 'object',
        'properties': {},
    }

    for name, field in form.base_fields.items():
        schema['properties'][name] = get_field_schema(name, field)
        if field.required:
            schema.setdefault('required', []).append(name)

    return schema
899851
def org_registration_form(org_model):
    

    class OrganizationRegistrationForm(forms.ModelForm):
        """Form class for creating new organizations owned by new users."""
        email = forms.EmailField()

        class Meta:
            model = org_model
            exclude = ("is_active", "users")

        def save(self, *args, **kwargs):
            self.instance.is_active = False
            super(OrganizationRegistrationForm, self).save(*args, **kwargs)

    return OrganizationRegistrationForm
381108
def xmlobjectform_factory(model, form=XmlObjectForm, fields=None, exclude=None,
                          widgets=None, max_num=None, label=None, can_delete=True,
                          extra=None, can_order=False):
    

    attrs = {'model': model}
    if fields is not None:
        attrs['fields'] = fields
    if exclude is not None:
        attrs['exclude'] = exclude
    if widgets is not None:
        attrs['widgets'] = widgets
    if max_num is not None:
        attrs['max_num'] = max_num
    if extra is not None:
        attrs['extra'] = extra
    if can_delete is not None:
        attrs['can_delete'] = can_delete
    if can_order is not None:
        attrs['can_order'] = can_order

    # If parent form class already has an inner Meta, the Meta we're
    # creating needs to inherit from the parent's inner meta.
    parent = (object,)
    if hasattr(form, 'Meta'):
        parent = (form.Meta, object)
    Meta = type(str('Meta'), parent, attrs)

    # Give this new form class a reasonable name.
    class_name = model.__name__ + str('XmlObjectForm')

    # Class attributes for the new form class.
    form_class_attrs = {
        'Meta': Meta,
        # django has a callback formfield here; do we need that?
        # label for a subform/formset
        'form_label': label,
    }

    return XmlObjectFormType(class_name, (form,), form_class_attrs)
1346091
def form_valid(self, forms):
        
        for key, form in forms.items():
            setattr(self, '{}_object'.format(key), form.save())
        return super(MultipleModelFormMixin, self).form_valid(forms)
1086385
def mangle_form(form):
    ""
    for field, widget in form.fields.iteritems():
        if type(widget) is forms.widgets.TextInput:
            form.fields[field].widget = PaperTextInput()
            form.fields[field].label = ''
        if type(widget) is forms.widgets.PasswordInput:
            field.widget = PaperPasswordInput()
            field.label = ''
    return form
684058
function documentFactory(validators) {
    function documentValidator(doc, attr, debug) {
      doc = doc || {};
      attr = attr || {};
      
      var errors = [];

      _.each(validators, function (valset, field) {
        var err = null;
        var value = doc[field];

        // turn validators into an array if it isn't one
        valset = _.arrayify(valset);

        // run all the validation for this field
        _.each(valset, function (validator) {

          // if there's already an error, don't bother
          if (err) return;
          err = validator(value, attr, (field == 'badge'));

        });

        // set the correct field on the error
        if (err) err.field = field;

        // jam it into the array with the rest of 'em
        errors.push(err);
      });

      // throw out any undefined or nulls that snuck in there
      errors = _.reject(errors, _.isMissing);

      if (errors.length) {
        return { name: 'doc', errors: errors };
      }
    }
    documentValidator.meta = { name : 'doc' };
    return documentValidator;
  }
229469
def render_form(form):
    """"""

    if 'crispy_forms' in settings.INSTALLED_APPS:
        from crispy_forms.templatetags.crispy_forms_filters import as_crispy_form
        return as_crispy_form(form)

    template = get_template("bootstrap/form.html")
    form = _preprocess_fields(form)

    return template.render({"form": form})
1271251
function getFormApps(connections, options, cb) {
  var validate = validation(options);
  function validateParams(cb) {
    validate.has("formId",cb);
  }
  validateParams(function(err) {
    if (err) {
      return cb(err);
    }
    var conn = connections.mongooseConnection;
    var appFormsModel = models.get(conn, models.MODELNAMES.APP_FORMS);
    var formId = options.formId;
    var restrictToUser = options.restrictToUser;

    groups.validateFormAllowedForUser(connections, restrictToUser, formId, function(err) {
      if (err) {
        return cb(err);
      }

      groups.getAppsForUser(connections, restrictToUser, function(err, allowedApps) {
        var query = {forms: formId};
        if (allowedApps) {
          query.apps = {$in: allowedApps};
        }
        appFormsModel.find(query).exec(function(err, apps) {
          if (err) {
            return cb(err);
          }
          return cb(null, apps);
        });
      });

    });
  });
}