Ejemplo n.º 1
0
    def get(self,item_id=None):
        from auth.models import User
        if 'page' in request.endpoint:
            from page.models import Page
            page = Page.get_by_id(item_id)
            if not 'content' in request.endpoint:
                self._form = model_form(Page,Page.session,base_class=Form,exclude=['added_by','date_added'])
                self._context['obj'] = page
            else:
                from page.forms import EditContentForm
                self._form = EditContentForm
            self._form_obj = page
        elif 'block' in request.endpoint:
            from page.models import Block
            block = Block.get_by_id(item_id)
            if not 'content' in request.endpoint:
                self._form = model_form(Block,Block.session,base_class=Form,exclude=['templates','pages'])
                self._context['obj'] = block
            else:
                from page.forms import EditContentForm
                self._form = EditContentForm
            self._form_obj = block
        else:
            from admin.forms import TemplateBodyFieldForm
            from wtforms import FormField
            from page.models import Template
            template = Template.get_by_id(item_id)
            form = model_form(Template,Template.session,base_class=Form,exclude=['pages','blocks','filename','body'])

            class TemplateForm(form):
                body = FormField(TemplateBodyFieldForm,separator='_')
            self._form = TemplateForm
            self._context['obj'] = template
            self._form_obj = template
        return self.render()
Ejemplo n.º 2
0
        def edit(model_name, model_key):
            """
            Edit a particular instance of a model.
            """
            if not model_name in model_dict.keys():
                return "%s cannot be accessed through this admin page" % (
                    model_name,)

            model = model_dict[model_name]
            model_form = admin_blueprint.form_dict[model_name]

            pk = _get_pk_name(model)
            pk_query_dict = {pk: model_key}

            try:
                model_instance = db_session.query(model).filter_by(
                    **pk_query_dict).one()
            except NoResultFound:
                return "%s not found: %s" % (model_name, model_key)

            if request.method == 'GET':
                form = model_form(obj=model_instance)
                has_file_field = filter(lambda field: isinstance(field, wtf_fields.FileField), form)
                return render_template(
                    'admin/edit.html',
                    admin_models=sorted(model_dict.keys()),
                    model_instance=model_instance,
                    model_name=model_name, form=form, has_file_field=has_file_field)

            elif request.method == 'POST':
                form = model_form(request.form, obj=model_instance)
                has_file_field = filter(lambda field: isinstance(field, wtf_fields.FileField), form)
                if form.validate():
                    model_instance = _populate_model_from_form(
                        model_instance, form)
                    db_session.add(model_instance)
                    db_session.commit()
                    flash('%s updated: %s' % (model_name, model_instance),
                          'success')
                    return redirect(
                        url_for('.list_view',
                                model_name=model_name))
                else:
                    flash('There was an error processing your form. '
                          'This %s has not been saved.' % model_name,
                          'error')
                    return render_template(
                        'admin/edit.html',
                        admin_models=sorted(model_dict.keys()),
                        model_instance=model_instance,
                        model_name=model_name, form=form, has_file_field=has_file_field)
Ejemplo n.º 3
0
def client_sensor_edit(client_id, sensor_id):
    with app.db.session_scope():
        sensor = app.db.get_sensor(sensor_id)
        MyForm = model_form(Sensor, \
                        base_class=Form, \
                        db_session=app.db.get_session(),
                        exclude=['core_device', 'name', 'reference', 'incremental', 'formula', 'data_type', 'conversion', 'last_value', 'last_received', 'history_duplicate','value_min','value_max'])
        #MyForm.history_duplicate.kwargs['validators'] = []
        MyForm.history_store.kwargs['validators'] = []
        form = MyForm(request.form, sensor)

        if request.method == 'POST' and form.validate():
            if request.form['history_store'] == 'y':
                store = 1 
            else:
                store = 0
            app.db.update_sensor(sensor_id, \
                     history_round=request.form['history_round'], \
                     history_store=store, \
                     history_max=request.form['history_max'], \
                     history_expire=request.form['history_expire'],
                     timeout=request.form['timeout'])

            flash(gettext("Changes saved"), "success")
            return redirect("/client/{0}/dmg_devices/known".format(client_id))
            pass
        else:
                return render_template('client_sensor.html',
                form = form,
                clientid = client_id,
                mactive="clients",
                active = 'devices'
                )
Ejemplo n.º 4
0
def form_for(model_class, timestamp_mixin=True, exclude=None, skip=[]):

    if timestamp_mixin and exclude:
        exclude = exclude + ['created_on','created_by','creator_id','updated_on','updated_by','updater_id']
    elif timestamp_mixin and not exclude:
        exclude = ['created_on','created_by','creator_id','updated_on','updated_by','updater_id']

    form_model_base = model_form(model_class, Form, exclude=exclude, converter=CrudModelConverter())

    def _populate_obj(self, obj):
        skip_fields = ['UploadImageField','UploadField','FieldList']
        for name, field in self._fields.iteritems():
            if not name in self.skip and not type(field).__name__ in skip_fields:
                field.populate_obj(obj, name)

    def _pre_process_content(self):
        pass

    Frm = type("CrudExtraBaseForm", (form_model_base,), { 
        'source_class' : model_class,
        'skip': skip,
        'populate_obj': _populate_obj,
        'pre_process_content': _pre_process_content,
    })

    return Frm
Ejemplo n.º 5
0
def getform(request, sub_id, domain):
    """
    Returns a metadata form tailored to the given domain.
    """

    domain = domain.lower()
    if domain in metadata_classes():
        meta = metadata_classes()[domain]()
    else:
        from b2share_model.model import SubmissionMetadata
        meta = SubmissionMetadata()

    if not is_current_user_allowed_to_deposit(meta):
        return render_template('b2share-addmeta-table-denied.html')

    MetaForm = model_form(meta.__class__, base_class=FormWithKey,
                          exclude=['submission', 'submission_type'],
                          field_args=meta.field_args,
                          converter=HTML5ModelConverter())
    meta_form = MetaForm(request.form, meta)

    return render_template(
        'b2share-addmeta-table.html',
        sub_id=sub_id,
        metadata=meta,
        form=meta_form,
        getattr=getattr)
Ejemplo n.º 6
0
def persons_edit(person_id):
    with app.db.session_scope():
        if person_id > 0:
            person = app.db.get_person(person_id)
	else:
            personn = None

	MyForm = model_form(Person, \
			base_class=Form, \
			db_session=app.db.get_session(),
			exclude=['user_accounts'])
	form = MyForm(request.form, person)
        if request.method == 'POST' and form.validate():
	    if int(person_id) > 0:
                app.db.update_person(person_id, \
					p_first_name=request.form['first_name'], \
					p_last_name=request.form['last_name'], \
					p_birthdate=request.form['birthdate'])
	    else:
                app.db.add_person(\
					p_first_name=request.form['first_name'], \
					p_last_name=request.form['last_name'], \
					p_birthdate=request.form['birthdate'])
            flash(gettext("Changes saved"), "success")
            return redirect("/persons")
	    pass
	elif request.method == 'POST' and not form.validate():
	    flash(gettext("Invalid input"), "error")    	

    return render_template('person_edit.html',
            form = form,
            personid = person_id,
            mactve="auth",
            )
Ejemplo n.º 7
0
def index():
    """
    Generates the main page and the automatic form using a generic AppItem object

    :return: the template to be served to the client
    """

    params = {'title': 'Main'}
    app_item = AppItem()
    # crates a model class from the application item
    app_item_form = model_form(AppItem, db.session, base_class=Form, field_args=app_item.field_args)

    login_form = LoginForm(request.form)
    if helpers.validate_form_on_submit(login_form):
        user = login_form.get_user()
        login.login_user(user)
        params['retry_login'] = False

        # redirect to prevent form double submit
        return redirect(request.url)
    else:
        if login_form.errors:
            params['retry_login'] = True

    params['is_authenticated'] = login.current_user.is_authenticated()

    check_errors()

    return render_template('index.html',
                           params=params,
                           form=app_item_form(obj=app_item),
                           login_form=login_form,
                           app_config=ActiveConfig)
Ejemplo n.º 8
0
class LoginForm(model_form(User, base_class=Form, exclude=['first_name', 'last_name'],
                           field_args=User.get_field_args_login())):
    """
    Class representing the form handling authentication in the admin area.
    """

    def validate_username(self, field):
        del field

        user = self.get_user()

        if user is None:
            raise validators.ValidationError('Username does not exist.')

    def validate_password(self, field):
        del field

        user = self.get_user()
        if user is None:
            return

        if not check_password_hash(user.password, self.password.data):
            raise validators.ValidationError('Password is invalid.')

    def get_user(self):
        return User.query.filter_by(username=self.username.data).first()
Ejemplo n.º 9
0
def index():
    from models import User, Post

    post_form_class = model_form(Post, base_class=Form, db_session=db.session)

    if request.method == 'POST':
        # For full example:
        # http://flask.pocoo.org/snippets/60/

        # alternative:
        # https://wtforms-alchemy.readthedocs.org/en/latest/introduction.html
        user = User.query.filter_by(username='******').first()
        print("{} is creating a new {}'th post!".format(
            user.username,
            len(user.posts.all()) + 1))

        form = post_form_class(request.form)
        if form.validate():
            post = Post(**form.data)
            db.session.add(post)
            db.session.commit()

            flash('Post created!')
        else:
            flash('Form is not valid! Post was not created.')

    else:
        form = post_form_class()

    posts = Post.query.all()
    return render_template('home.html', form=form, posts=posts)
Ejemplo n.º 10
0
 def get_form(self, adding=False):
     return model_form(self.model,
                       base_class=BaseForm,
                       only=self.only,
                       exclude=self.exclude,
                       field_args=self.field_args,
                       converter=AdminModelConverter(self))
Ejemplo n.º 11
0
def user(id=0):
    user = User.query.get(id)
    form = model_form(User, base_class=Form, db_session=db.session, # автоматическая генерация класса формы
            field_args = dict([(c.name, {'label': c.doc}) for c in User.__table__.columns if c.doc ],
            exclude = ['groups']))(request.form, obj = user)

    if request.method == 'POST' and form.validate_on_submit():
        if user:
            user.login=form.login.data
            user.uid=form.uid.data
            user.status=form.status.data
            user.email=form.email.data
            user.password=form.password.data
            user.first_login=form.first_login.data
            user.last_login=form.last_login.data
            user.cdate=form.cdate.data
            db.session.commit()
        else:
            user = User(request.form['login'] , request.form['password'], email=request.form['email'])
            db.session.add(user)
            db.session.commit()
        return redirect(url_for('index'))

    flash(u'Выбран id: %s' %  id)
    return render_template('edit.html', form=form)
Ejemplo n.º 12
0
 def get_form(self, adding=False):
     return model_form(self.model,
                       BaseForm,
                       only=self.only,
                       exclude=self.exclude,
                       field_args=self.field_args,
                       converter=AdminModelConverter(self))
Ejemplo n.º 13
0
def home():
    from models import User

    user_form_class = model_form(User, base_class=FlaskForm, db_session=db.session)

    if request.method == 'POST':
        form = user_form_class(request.form)
        if form.validate():
            try:
                model = User(**form.data)
                db.session.add(model)
                db.session.commit()
                flash('User created!')
                return redirect(url_for('home'))
            except IntegrityError:
                db.session.rollback()
                flash('This user is already exist')
            except Exception as ex:
                logger.error(ex)
                db.session.rollback()
                flash('Cant save user: '******'Someone have submitted an incorrect form!')
            flash('Invalid form. Please check fields')
    else:
        form = user_form_class()

    age18 = datetime.now() - timedelta(days=365.25 * 18)
    users = User.query.filter(User.birthday < age18)

    return render_template(
        'home.html',
        form=form,
        items=users,
    )
Ejemplo n.º 14
0
    def get(self, obj_id='', operation='', filter_name=''):
        if operation == 'new':
            #  we just want an empty form
            form = self.ObjForm()
            action = self.path
            return self.render_edit(form=form, action=action)

        if operation == 'delete':
            obj = self.model.query.get(obj_id)
            db.session.delete(obj)
            db.session.commit()
            return redirect(self.path)

        if obj_id:
            #Dynamically create form fields based on db Model
            ObjForm = model_form(self.model, db.session)

            obj = self.model.query.get(obj_id)

            #populate form
            form = self.ObjForm(obj=obj)

            # action is the url that we will later use to POST data
            action = request.path
            return self.render_edit(form=form, action=action)

        obj = self.model.query.order_by(self.model.date_Created.desc()).all()

        #choosing which template to display
        if self.path == "/refineryApp/":
            return self.render_refineryApp(obj=obj)
        elif "Category" in str(obj):
            return self.render_Category(obj=obj)
        elif "Workflow" in str(obj):
            return self.render_Workflows(obj=obj)
Ejemplo n.º 15
0
def client_sensor_edit(client_id, sensor_id):
    with app.db.session_scope():
        sensor = app.db.get_sensor(sensor_id)
        MyForm = model_form(Sensor, \
                        base_class=Form, \
                        db_session=app.db.get_session(),
                        exclude=['core_device', 'name', 'reference', 'incremental', 'formula', 'data_type', 'conversion', 'last_value', 'last_received', 'history_duplicate'])
        #MyForm.history_duplicate.kwargs['validators'] = []
        MyForm.history_store.kwargs['validators'] = []
        form = MyForm(request.form, sensor)

        if request.method == 'POST' and form.validate():
            if request.form['history_store'] == 'y':
                store = 1
            else:
                store = 0
            app.db.update_sensor(sensor_id, \
                     history_round=request.form['history_round'], \
                     history_store=store, \
                     history_max=request.form['history_max'], \
                     history_expire=request.form['history_expire'])

            flash(gettext("Changes saved"), "success")
            return redirect("/client/{0}/devices/known".format(client_id))
            pass
        else:
            return render_template('client_sensor.html',
                                   form=form,
                                   clientid=client_id,
                                   mactve="clients",
                                   active='devices')
Ejemplo n.º 16
0
def create_or_update_model(kls, base_object=None, supplied_data=None):
  # TODO: I don't like the "error" here...

  # Create a form based upon the SQLAlchemy model
  model = kls() if not base_object else base_object
  if hasattr(kls, "Form"):
    # If the class has a handmade WTForm built, use that for validation
    MyForm = kls.Form
  else:
    # Otherwise generate the form dynamically
    MyForm = model_form(kls, wtf.Form)
  if supplied_data:
    data = MultiDict(supplied_data)
  else:
    data = flask.request.form
  form = MyForm(data, model)

  # Ensure it is a POST/PUT or data supplied by another function
  if flask.request.method in ["POST", "PUT"] or supplied_data:
    # If there are issues, note them, otherwise create/update the model
    if form.validate():
      try:
        form.populate_obj(model)
        db.session.add(model)
        db.session.commit()
        return dict(model=model, success=True)
      except SQLAlchemyError, e:
        if app.debug:
          # If we're in debug mode, re-raise so we get the debugger
          raise e
        else:
          # If in production ... uh-oh
          # TODO: Push over to a 500?
          flask.flash("Database error...", "alert-error")
Ejemplo n.º 17
0
 def test_no_mro(self):
     converter = ModelConverter(use_mro=False)
     # Without MRO, will not be able to convert 'grade'
     self.assertRaises(ModelConversionError, model_form, self.Course, self.sess, converter=converter)
     # If we exclude 'grade' everything should continue working
     F = model_form(self.Course, self.sess, exclude=['grade'], converter=converter)
     self.assertEqual(len(list(F())), 7)
Ejemplo n.º 18
0
def edit(request):
    """ edit(request)
        no return value, called with route_url('apex_edit', request)

        This function will only work if you have set apex.auth_profile.

        This is a very simple edit function it works off your auth_profile
        class, all columns inside your auth_profile class will be rendered.
    """
    title = _('Edit')

    ProfileForm = model_form(
        model=get_module(apex_settings('auth_profile')),
        base_class=ExtendedForm,
        exclude=('id', 'user_id'),
    )

    record = AuthUser.get_profile(request)
    form = ProfileForm(obj=record)
    if request.method == 'POST' and form.validate():
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        flash(_('Profile Updated'))
        return HTTPFound(location=request.url)

    return {'title': title, 'form': form, 'action': 'edit'}
Ejemplo n.º 19
0
def getform(request, sub_id, domain):
    """
    Returns a metadata form tailored to the given domain.
    """

    domain = domain.lower()
    if domain in metadata_classes():
        meta = metadata_classes()[domain]()
    else:
        from b2share_model.model import SubmissionMetadata
        meta = SubmissionMetadata()

    if not is_current_user_allowed_to_deposit(meta):
        return render_template('b2share-addmeta-table-denied.html')

    MetaForm = model_form(meta.__class__,
                          base_class=FormWithKey,
                          exclude=['submission', 'submission_type'],
                          field_args=meta.field_args,
                          converter=HTML5ModelConverter())
    meta_form = MetaForm(request.form, meta)

    return render_template('b2share-addmeta-table.html',
                           sub_id=sub_id,
                           metadata=meta,
                           form=meta_form,
                           getattr=getattr)
Ejemplo n.º 20
0
    def post(self, item_id=None):
        from page.models import StaticBlock
        form = model_form(StaticBlock,
                          StaticBlock.session,
                          base_class=Form,
                          exclude=['content'])

        class StaticBlockForm(form):
            content = FormField(TextEditorFieldForm, '_')

        self._form = StaticBlockForm
        if item_id is None:
            block = StaticBlock()
            msg = "created a new"
        else:
            block = StaticBlock.get_by_id(item_id)
            msg = "updated a"
        data = self.get_form_data()
        block.name = data['name']
        block.content = data['content']['content']
        block.block_id = data['block_id']
        if block.save():
            flash(msg + " static_block with id: {}".format(block.block_id))
            return self.redirect('admin.index')
        else:
            flash("Error")
        return self.render()
Ejemplo n.º 21
0
def posts_of_user():
    posts = Post.query.all()
    if not current_user.is_authenticated:
        return render_template('posts.html', posts=posts)
    else:
        post_form_class = model_form(Post, base_class=Form, db_session=db.session)
        if request.method == 'POST':
            print("{} is creating a new {}'th post!".format(
                current_user.username, len(current_user.posts.all()) + 1))

            form = post_form_class(request.form)
            if form.validate():
                if request.form['submit'] == 'DELETE':
                    post_to_delete = Post.query.filter_by(id=str(request.form['menu'])).first()
                    db.session.delete(post_to_delete)
                    db.session.commit()
                    flash('Post deleted!')
                    pass
                elif request.form['submit'] == 'Submit':
                    post = Post(user=current_user, title=form.data['title'], content=form.data['content'])
                    db.session.add(post)
                    db.session.commit()

                    flash('Post created!')
                else:
                    flash('Form is not valid! Post was not created.')
        else:
            form = post_form_class()

        return render_template('home.html', form=form, posts=posts)
Ejemplo n.º 22
0
def edit(request):
    """ edit(request)
        no return value, called with route_url('apex_edit', request)

        This function will only work if you have set apex.auth_profile.

        This is a very simple edit function it works off your auth_profile
        class, all columns inside your auth_profile class will be rendered.
    """
    title = _('Edit')

    ProfileForm = model_form(
        model=get_module(apex_settings('auth_profile')),
        base_class=ExtendedForm,
        exclude=('id', 'user_id'),
    )

    record = AuthUser.get_profile(request)
    form = ProfileForm(obj=record)
    if request.method == 'POST' and form.validate():
        record = merge_session_with_post(record, request.POST.items())
        DBSession.merge(record)
        DBSession.flush()
        flash(_('Profile Updated'))
        return HTTPFound(location=request.url)

    return {'title': title, 'form': form, 'action': 'edit'}
Ejemplo n.º 23
0
def index():
    from models import User, Post

    post_form_class = model_form(Post, base_class=Form, db_session=db.session)

    if request.method == 'POST':
        # For full example:
        # http://flask.pocoo.org/snippets/60/

        # alternative:
        # https://wtforms-alchemy.readthedocs.org/en/latest/introduction.html
        user = User.query.filter_by(username='******').first()
        print("{} is creating a new {}'th post!".format(
            user.username, len(user.posts.all()) + 1))

        form = post_form_class(request.form)
        if form.validate():
            post = Post(**form.data)
            db.session.add(post)
            db.session.commit()

            flash('Post created!')
        else:
            flash('Form is not valid! Post was not created.')

    else:
        form = post_form_class()

    posts = Post.query.all()
    return render_template('home.html', form=form, posts=posts)
Ejemplo n.º 24
0
 def post(self,item_id=None):
     from ext import db
     from auth.models import User
     if 'content' in request.endpoint:
         session['content'] = request.form['content'][:]
         return self.redirect('admin.edit_{}'.format(request.url.split('/')[-3]),item_id='{}'.format(request.url.split('/')[-1]))
     else:
         if 'page' in request.endpoint:
             from page.models import Page as model
             needs_content = True
             msg = 'cms page'
             redirect = 'pages'
             exclude = ['added_by','date_added']
         if 'block' in request.endpoint:
             from page.models import Block as model
             needs_content = True
             msg = 'cms block'
             redirect = 'blocks'
             exclude = ['templates','pages']
         if 'template' in request.endpoint:
             from page.models import Template as model
             needs_content = False
             msg = 'template'
             redirect = 'templates'
             exclude = ['pages','blocks']
         self._form = model_form(model,db.session,base_class=Form,exclude=exclude)(request.form)
         obj = model.query.filter(model.id==item_id).first()
         self._form.populate_obj(obj)
         if needs_content:
             if 'content' in session:
                 obj.content = session.pop('content',None)
         obj.update()
         flash('Successfully updated {}: {}'.format(msg,obj.name))
         return self.redirect('admin.{}'.format(redirect))
Ejemplo n.º 25
0
 def post(self):
     from page.models import Template
     from auth.models import User
     from ext import db
     self._form = model_form(Template,db.session,base_class=Form,exclude=['blocks','pages','body'])(request.form)
     if self._form.validate():
         template = Template()
         self._form.populate_obj(template)
         template.save()
         filename = template.filename
         if template.body is not None:
             body = template.body[:]
         else:
             body = ''
         from settings import BaseConfig
         import os
         templatedir = os.path.join(BaseConfig.ROOT_PATH,'templates')
         os.system('touch {}'.format(os.path.join(templatedir,filename)))
         fp = open(os.path.join(templatedir,filename),'w')
         fp.write(body+'\n')
         fp.close()
         flash('you have created a new template named: {}'.format(template.name))
         return self.redirect('admin.templates')
     else:
         flash('You need to give the template a name')
     return self.render()
Ejemplo n.º 26
0
 def post(self,item_id=None):
     from ext import db
     from auth.models import User
     if 'content' in request.endpoint:
         session['content'] = request.form['content'][:]
         return self.redirect('admin.edit_{}'.format(request.url.split('/')[-3]),item_id='{}'.format(request.url.split('/')[-1]))
     else:
         if 'page' in request.endpoint:
             from page.models import Page as model
             needs_content = True
             msg = 'cms page'
             redirect = 'pages'
             exclude = ['added_by','date_added']
         if 'block' in request.endpoint:
             from page.models import Block as model
             needs_content = True
             msg = 'cms block'
             redirect = 'blocks'
             exclude = ['templates','pages']
         if 'template' in request.endpoint:
             from page.models import Template as model
             needs_content = False
             msg = 'template'
             redirect = 'templates'
             exclude = ['pages','blocks']
         self._form = model_form(model,db.session,base_class=Form,exclude=exclude)(request.form)
         obj = model.query.filter(model.id==item_id).first()
         self._form.populate_obj(obj)
         if needs_content:
             if 'content' in session:
                 obj.content = session.pop('content',None)
         obj.update()
         flash('Successfully updated {}: {}'.format(msg,obj.name))
         return self.redirect('admin.{}'.format(redirect))
Ejemplo n.º 27
0
 def post(self):
     from page.models import Template
     from auth.models import User
     from ext import db
     self._form = model_form(Template,db.session,base_class=Form,exclude=['blocks','pages','body'])(request.form)
     if self._form.validate():
         template = Template()
         self._form.populate_obj(template)
         template.save()
         filename = template.filename
         if template.body is not None:
             body = template.body[:]
         else:
             body = ''
         from settings import BaseConfig
         import os
         templatedir = os.path.join(BaseConfig.ROOT_PATH,'templates')
         os.system('touch {}'.format(os.path.join(templatedir,filename)))
         fp = open(os.path.join(templatedir,filename),'w')
         fp.write(body+'\n')
         fp.close()
         flash('you have created a new template named: {}'.format(template.name))
         return self.redirect('admin.templates')
     else:
         flash('You need to give the template a name')
     return self.render()
Ejemplo n.º 28
0
def persons_edit(person_id):
    with app.db.session_scope():
        if person_id > 0:
            person = app.db.get_person(person_id)
        else:
            personn = None

        MyForm = model_form(Person, \
          base_class=Form, \
          db_session=app.db.get_session(),
          exclude=['user_accounts'])
        form = MyForm(request.form, person)

        if request.method == 'POST' and form.validate():
            if int(person_id) > 0:
                app.db.update_person(person_id, \
     p_first_name=request.form['first_name'], \
     p_last_name=request.form['last_name'], \
     p_birthdate=request.form['birthdate'])
            else:
                app.db.add_person(\
     p_first_name=request.form['first_name'], \
     p_last_name=request.form['last_name'], \
     p_birthdate=request.form['birthdate'])
            flash(gettext("Changes saved"), "success")
            return redirect("/persons")
            pass
        elif request.method == 'POST' and not form.validate():
            flash(gettext("Invallid input"), "error")

    return render_template('person_edit.html',
                           form=form,
                           personid=person_id,
                           mactve="auth")
Ejemplo n.º 29
0
 def test_convert_basic(self):
     self.assertRaises(TypeError, model_form, None)
     self.assertRaises(ModelConversionError, model_form, self.Course)
     form_class = model_form(self.Course, exclude=['students'])
     form = form_class()
     self.assertEqual(len(list(form)), 4)
     assert isinstance(form.cost, fields.DecimalField)
Ejemplo n.º 30
0
def edit_user(username):
    current_app.logger.debug(f"Edit User View, user: {username}")
    user = User.query.filter_by(username=username).scalar()
    UserForm = model_form(
        User, db_session=db.session, base_class=FlaskForm,
        exclude=['password', 'created_on', 'last_login']
    )
    UserForm.is_admin.kwargs['validators'] = []
    UserForm.is_activated.kwargs['validators'] = []
    user_form = UserForm(obj=user)

    if user_form.validate_on_submit():
        user.name = user_form.name.data
        user.username = user_form.username.data
        user.email = user_form.email.data
        user.is_activated = user_form.is_activated.data
        user.is_admin = user_form.is_admin.data
        user.db_commit()

        return redirect(url_for('admin_bp.users'))
    else:
        current_app.logger.debug(user_form.errors)

    return render_template(
        'edit_users.html',
        user=user,
        form=user_form,
        title='Admin Panel - Edit User',
        template="admin-page",
    )
Ejemplo n.º 31
0
    def get(self, obj_id='', operation='', filter_name=''):
        if operation == 'new':
            #  we just want an empty form
            form = self.ObjForm()
            action = self.path
            return self.render_detail(form=form, action=action)

        if operation == 'delete':
            obj = self.model.query.get(obj_id)
            db.session.delete(obj)
            db.session.commit()
            return redirect(self.path)

        # list view with filter
        if operation == 'filter':
            func = self.filters.get(filter_name)
            obj = func(self.model)
            return self.render_list(obj=obj, filter_name=filter_name)

        if obj_id:
            # this creates the form fields base on the model
            # so we don't have to do them one by one
            ObjForm = model_form(self.model, db.session)

            obj = self.model.query.get(obj_id)
            # populate the form with our blog data
            form = self.ObjForm(obj=obj)
            # action is the url that we will later use
            # to do post, the same url with obj_id in this case
            action = request.path
            return self.render_detail(form=form, action=action)

        obj = self.model.query.order_by(self.model.created_on.desc()).all()
        return self.render_list(obj=obj)
Ejemplo n.º 32
0
    def get(self):
        if not 'content' in request.endpoint:
            from page.models import Page
            from wtforms import FormField
            from admin.forms import BaseTemplateForm
            from auth.models import User
            from page.models import Template
            self._context['choices'] = [(x, x.name)
                                        for x in Template.query.all()]
            form = model_form(Page,
                              Page.session,
                              base_class=Form,
                              exclude=['date_added', 'added_by'])

            class PageForm(form):
                template = FormField(BaseTemplateForm)

                def __init__(self, *args, **kwargs):
                    if 'prefix' in kwargs:
                        kwargs.pop('prefix')
                    super(PageForm, self).__init__(*args, **kwargs)

            self._form = PageForm(prefix=False)
        else:
            from page.forms import EditContentForm
            from auth.models import User
            self._form = EditContentForm
        return self.render()
Ejemplo n.º 33
0
Archivo: app.py Proyecto: andyzt/tceh
def index():
    from models import User, Post

    post_form_class = model_form(Post, base_class=Form, db_session=db.session)

    if request.method == 'POST':

        form = post_form_class(request.form)
        if form.validate():

            post = Post(**form.data)
            post.is_visible = True

            print("{} is creating a new {}'th post!".format(
               post.user.username, len(post.user.posts.all()) + 1))

            db.session.add(post)
            db.session.commit()
            flash('Post created!')

        else:
            flash('Form is not valid! Post was not created.')

    else:
        form = post_form_class()

    posts = Post.query.filter_by(is_visible=True).all()
    return render_template('home.html', form=form, posts=posts)
Ejemplo n.º 34
0
    def get(self, obj_id='', operation='', filter_name=''):
        if operation == 'new':
            #  we just want an empty form
            form = self.ObjForm()
            action = self.path
            return self.render_detail(form=form, action=action)
            
        if operation == 'delete':
            obj = self.model.query.get(obj_id)
            db.session.delete(obj)
            db.session.commit()
            return redirect(self.path)

        # list view with filter
        if operation == 'filter':
            func = self.filters.get(filter_name)
            obj = func(self.model)
            return self.render_list(obj=obj, filter_name=filter_name)


        if obj_id:
            # this creates the form fields base on the model
            # so we don't have to do them one by one
            ObjForm = model_form(self.model, db.session)

            obj = self.model.query.get(obj_id)
            # populate the form with our blog data
            form = self.ObjForm(obj=obj)
            # action is the url that we will later use
            # to do post, the same url with obj_id in this case
            action = request.path
            return self.render_detail(form=form, action=action)

        obj = self.model.query.order_by(self.model.created_on.desc()).all()
        return self.render_list(obj=obj)
Ejemplo n.º 35
0
def client_devices_edit(client_id, did):
    with app.db.session_scope():
        device = app.db.get_device_sql(did)
        MyForm = model_form(Device, \
                        base_class=Form, \
                        db_session=app.db.get_session(),
                        exclude=['params', 'commands', 'sensors', 'address', 'xpl_commands', 'xpl_stats', 'device_type_id', 'client_id', 'client_version'])
        form = MyForm(request.form, device)

        if request.method == 'POST' and form.validate():
            # save it
            app.db.update_device(did, \
                    d_name=request.form['name'], \
                    d_description=request.form['description'], \
                    d_reference=request.form['reference'])
            # message the suer
            flash(gettext("Device saved"), 'success')
            # reload stats
            req = MQSyncReq(app.zmq_context)
            msg = MQMessage()
            msg.set_action( 'reload' )
            resp = req.request('xplgw', msg.get(), 100)
            # redirect
            return redirect("/client/{0}/dmg_devices/known".format(client_id))
        else:
            return render_template('client_device_edit.html',
                form = form,
                clientid = client_id,
                mactive="clients",
                active = 'devices'
                )
Ejemplo n.º 36
0
    def __init__(self,
                 model,
                 endpoint,
                 Categories_template=None,
                 Workflows_template=None,
                 refineryApp_template=None,
                 edit_template=None,
                 exclude=None,
                 filters=None):
        self.model = model
        self.endpoint = endpoint
        self.path = url_for('.%s' % self.endpoint)

        #templates based on URL
        if self.endpoint == "/refineryApp/category/":
            self.Categories_template = Categories_template
        if self.endpoint == "/refineryApp/workflows/":
            self.Workflows_template = Workflows_template
        if self.endpoint == "/refineryApp/":
            self.refineryApp_template = refineryApp_template
        if edit_template:
            self.edit_template = edit_template

        self.filters = filters or {}
        #Form will dynamically handle any db object
        self.ObjForm = model_form(self.model, db.session, exclude=exclude)
Ejemplo n.º 37
0
def _form_for_model(model_class, db_session, exclude=None, exclude_pk=True):
    """Return a form for a given model. This will be a form generated
    by wtforms.ext.sqlalchemy.model_form, but decorated with a
    QuerySelectField for foreign keys.
    """
    if not exclude:
        exclude = []

    model_mapper = sa.orm.class_mapper(model_class)
    relationship_fields = []

    pk_names = _get_pk_names(model_class)

    if exclude_pk:
        exclude.extend(pk_names)

    # exclude any foreign_keys that we have relationships for;
    # relationships will be mapped to select fields by the
    # AdminConverter
    exclude.extend([relationship.local_side[0].name
                    for relationship in model_mapper.iterate_properties
                    if isinstance(relationship,
                                  sa.orm.properties.RelationshipProperty)
                    and relationship.local_side[0].name not in pk_names])
    form = model_form(model_class, exclude=exclude,
                      converter=AdminConverter(db_session))

    return form
Ejemplo n.º 38
0
    def post(self, obj_id=''):
        try:
            # either load and object to update if obj_id is given
            # else initiate a new object, this will be helpfull
            # when we want to create a new object instead of just
            # editing existing one
            if obj_id:
                obj = self.model.query.get(obj_id)
            else:
                obj = self.model()

            ObjForm = model_form(self.model, db.session)
            # populate the form with the request data
            form = self.ObjForm(request.form)
            # this actually populates the obj (the blog post)
            # from the form, that we have populated from the request post
            pre_obj_dict = self._copy_obj(obj)
            form.populate_obj(obj)
            changes = self._delta(dict_pre=pre_obj_dict, obj_post=obj)
            db.session.add(obj)
            db.session.commit()
            # process triggers on actions initiated by user
            dispatcher.send(signal=Constant.SIGNAL_UI_DB_POST,
                            model=self.model,
                            row=obj,
                            last_commit_field_changed_list=changes)
            return redirect(self.path)
        except AttributeError as aex:
            L.l.error('Error CRUD POST {}'.format(aex))
            return redirect(self.path)
Ejemplo n.º 39
0
def client_devices_edit(client_id, did):
    with app.db.session_scope():
        device = app.db.get_device_sql(did)
        MyForm = model_form(Device, \
                        base_class=Form, \
                        db_session=app.db.get_session(),
                        exclude=['params', 'commands', 'sensors', 'address', 'xpl_commands', 'xpl_stats', 'device_type_id', 'client_id', 'client_version'])
        form = MyForm(request.form, device)

        if request.method == 'POST' and form.validate():
            # save it
            app.db.update_device(did, \
           d_name=request.form['name'], \
           d_description=request.form['description'], \
           d_reference=request.form['reference'])
            # message the suer
            flash(gettext("Device saved"), 'success')
            # reload stats
            req = MQSyncReq(app.zmq_context)
            msg = MQMessage()
            msg.set_action('reload')
            resp = req.request('xplgw', msg.get(), 100)
            # redirect
            return redirect("/client/{0}/devices/known".format(client_id))
        else:
            return render_template('client_device_edit.html',
                                   form=form,
                                   clientid=client_id,
                                   mactve="clients",
                                   active='devices')
Ejemplo n.º 40
0
    def get(self, item_id=None):
        from auth.models import User
        from ext import db
        if 'page' in request.endpoint:
            from page.models import Page
            page = Page.get_by_id(item_id)
            if not 'content' in request.endpoint:
                self._form = model_form(Page,
                                        db.session,
                                        base_class=Form,
                                        exclude=['added_by', 'date_added'])
                self._context['obj'] = page
            else:
                from page.forms import EditContentForm
                self._form = EditContentForm
            self._form_obj = page
        elif 'block' in request.endpoint:
            from page.models import Block
            block = Block.get_by_id(item_id)
            if not 'content' in request.endpoint:
                self._form = model_form(Block,
                                        db.session,
                                        base_class=Form,
                                        exclude=['templates', 'pages'])
                self._context['obj'] = block
            else:
                from page.forms import EditContentForm
                self._form = EditContentForm
            self._form_obj = block
        else:
            from admin.forms import TemplateBodyFieldForm
            from wtforms import FormField
            from page.models import Template
            template = Template.get_by_id(item_id)
            form = model_form(Template,
                              db.session,
                              base_class=Form,
                              exclude=['pages', 'blocks', 'filename', 'body'])

            class TemplateForm(form):
                body = FormField(TemplateBodyFieldForm, separator='_')

            self._form = TemplateForm
            self._context['obj'] = template
            self._form_obj = template
        return self.render()
Ejemplo n.º 41
0
def ModelForm(model, db_session, exclude=None):
    return model_form(
        model=model,
        db_session=db_session,
        base_class=Form,
        exclude_fk=False,
        exclude=exclude
        )
Ejemplo n.º 42
0
 def model_form(cls, *args, **kwargs):
     return model_form(
         model=cls,
         db_session=db.session,
         field_args={
             'category': {'widget': widgets.Select()}
         }
     )
Ejemplo n.º 43
0
Archivo: forms.py Proyecto: omh/yoshimi
 def __new__(self, model_class, session, data=None, obj=None, **kwargs):
     FormCls = model_form(
         model_class,
         base_class=ConflictPreventionForm,
         only=self._editable_properties(obj, Content),
         db_session=session,
     )
     return FormCls(data, obj, **kwargs)
Ejemplo n.º 44
0
Archivo: forms.py Proyecto: omh/yoshimi
 def __new__(self, model_class, session, data=None, obj=None, **kwargs):
     FormCls = model_form(
         model_class,
         base_class=ConflictPreventionForm,
         only=self._editable_properties(obj, Content),
         db_session=session,
     )
     return FormCls(data, obj, **kwargs)
Ejemplo n.º 45
0
 def _build_form(self):
     """build form for model class"""
     exclude = self.form_exclude or []
     exclude.append(get_pk_column(self.model).name)
     return model_form(self.model,
                       db_session=self.session,
                       only=self.form_only,
                       exclude=exclude,
                       field_args=self.form_field_args)
Ejemplo n.º 46
0
def addmeta(request, sub_id):
    """
    Checks the submitted metadata form for validity.
    Returns a new page with success message if valid, otherwise it returns a
    form with the errors marked.
    """
    if sub_id is None:
        #just return to deposit
        return redirect(url_for('.deposit'))

    CFG_B2SHARE_UPLOAD_FOLDER = current_app.config.get(
        "CFG_B2SHARE_UPLOAD_FOLDER")
    updir = os.path.join(CFG_B2SHARE_UPLOAD_FOLDER, sub_id)
    if (not os.path.isdir(updir)) or (not os.listdir(updir)):
        return render_template('500.html', message="Uploads not found"), 500

    domain = request.form['domain'].lower()
    if domain in metadata_classes():
        meta = metadata_classes()[domain]()
    else:
        from b2share_model.model import SubmissionMetadata
        meta = SubmissionMetadata()

    if not is_current_user_allowed_to_deposit(meta):
        return jsonify(
            valid=False,
            html=render_template('b2share-addmeta-table-denied.html'))

    MetaForm = model_form(meta.__class__,
                          base_class=FormWithKey,
                          exclude=['submission', 'submission_type'],
                          field_args=meta.field_args,
                          converter=HTML5ModelConverter())

    meta_form = MetaForm(request.form, meta)

    if meta_form.validate_on_submit():
        recid, marc = b2share_marc_handler.create_marc(request.form, sub_id,
                                                       current_user['email'],
                                                       meta)
        tmp_file = write_marc_to_temp_file(marc)
        # all usual tasks have priority 0; we want the bibuploads to run first
        from invenio.legacy.bibsched.bibtask import task_low_level_submission
        task_low_level_submission('bibupload', 'webdeposit', '--priority', '1',
                                  '-r', tmp_file)
        return jsonify(valid=True,
                       newurl=url_for("record.metadata", recid=recid),
                       html=render_template('record_waitforit.html',
                                            recid=recid,
                                            marc=marc))

    return jsonify(valid=False,
                   html=render_template('b2share-addmeta-table.html',
                                        sub_id=sub_id,
                                        metadata=meta,
                                        form=meta_form,
                                        getattr=getattr))
Ejemplo n.º 47
0
 def edit_form(element):
     ModelForm = model_form(element.__class__,
                            db_session=session,
                            base_class=Form)
     form = ModelForm(obj=element)
     if fields_whitelist:
         form._fields = dict((k, v) for (k, v) in form._fields.items()
                             if k in fields_whitelist)
     return form
Ejemplo n.º 48
0
 def test_convert_basic(self):
     self.assertRaises(TypeError, model_form, None)
     self.assertRaises(ModelConversionError, model_form, self.Course)
     form_class = model_form(self.Course, exclude=['students'])
     form = form_class()
     self.assertEqual(len(list(form)), 7)
     assert isinstance(form.cost, fields.DecimalField)
     assert isinstance(form.has_prereqs, fields.BooleanField)
     assert isinstance(form.started, fields.DateTimeField)
Ejemplo n.º 49
0
class UserEditForm(model_form(User, base_class=Form, field_args=User.get_field_args_create())):
    """
    Class representing the form handling the user editing from the admin area.
    """

    confirm = PasswordField('Repeat Password')

    def get_user(self):
        return User.query.filter_by(username=self.username.data).first()
Ejemplo n.º 50
0
 def model_form(cls, *args, **kwargs):
     return model_form(
         model=cls,
         db_session=db.session,
         field_args={
             'winning_level': {'widget': widgets.Select()},
             'rate': {'widget': widgets.Select()}
         }
     )
Ejemplo n.º 51
0
 def give_form(self):
     """
     Being called form child model class instance
     returns WTForms model_form object of corresponding model class.
     """
     form = model_form((eval(type(self).__name__)), db_session)
     print 'in give_form', type(self).__name__
     print form.data
     return form
Ejemplo n.º 52
0
 def _build_form(self):
     """build form for model class"""
     exclude = self.form_exclude or []
     exclude.append(get_pk_column(self.model).name)
     return model_form(self.model,  
                       db_session=self.session,
                       only=self.form_only, 
                       exclude=exclude, 
                       field_args=self.form_field_args)
Ejemplo n.º 53
0
 def create_form(element_class):
     ModelForm = model_form(element_class,
                            db_session=session,
                            base_class=Form)
     form = ModelForm()
     if fields_whitelist:
         form._fields = dict((k, v) for (k, v) in form._fields.items()
                             if k in fields_whitelist)
     return form
Ejemplo n.º 54
0
    def get_form(self, **kwargs):
        if self.wlw_model:
            mf = model_form(self.wlw_model,
                    base_class = self.wlw_form,
                    db_session = db.session,
                    only = self.wlw_only,
                    exclude = self.wlw_exclude,
                    field_args = kwargs)

        return mf
Ejemplo n.º 55
0
    def get_form(self, **kwargs):
        if self.wlw_model:
            mf = model_form(self.wlw_model,
                            base_class=self.wlw_form,
                            db_session=db.session,
                            only=self.wlw_only,
                            exclude=self.wlw_exclude,
                            field_args=kwargs)

        return mf
Ejemplo n.º 56
0
Archivo: app.py Proyecto: andyzt/tceh
def delete(post_id):
    from models import User, Post

    post_form_class = model_form(Post, base_class=Form, db_session=db.session)
    form = post_form_class()
    post = Post.query.filter_by(id=post_id).first()
    post.is_visible = False
    db.session.commit()
    posts = Post.query.filter_by(is_visible=True).all()
    return render_template('home.html', form=form, posts=posts)
Ejemplo n.º 57
0
 def get_form(self, obj=None):
     """
     Returns the form associated with this view if the form_class could
     not be found FormView tries to build the form using model_form
     function of wtforms sqlalchemy extension
     """
     if self.form_class:
         return self.form_class(request.form, obj=obj)
     return model_form(self.model_class, db_session=self.db.session)(
         request.form, obj=obj
     )
Ejemplo n.º 58
0
def home():
    if request.method == 'POST':
        Post.query.filter_by(id=request.form['id']).first().is_visible = False
        db.session.commit()
        print("Set invisible mark to post with id %s" %request.form['id'])

    post_form_class = model_form(Post, base_class=Form, db_session=db.session)
    form = post_form_class()
    posts = Post.query.filter_by(is_visible=True).all()

    return render_template('home.html', form=form, posts=posts)
Ejemplo n.º 59
0
def home():
    from models import Post

    post_form_class = model_form(
        Post,
        base_class=FlaskForm,
        db_session=db.session,
        exclude=['time_stamp'],
        field_args={
            'title': {
                'validators': [validators.Length(min=4, max=140)]
            },
            'text': {
                'widget': TextArea(),
                'validators': [validators.Length(min=10, max=3000)],
            },
            'author': {
                'validators': [
                    validators.Length(min=3, max=100),
                    validators.Regexp(
                        re.compile(r'\w+\s\w+[\s\w]+', re.U),
                        message="Type Author with format 'firstname lastname'")
                ]
            },
        })

    if request.method == 'POST':
        form = post_form_class(request.form)
        if form.validate():
            try:
                model = Post(**form.data)
                db.session.add(model)
                db.session.commit()
                flash('Your post added!')
                return redirect(url_for('home'))
            except IntegrityError:
                db.session.rollback()
                flash('This post is already exist')
            except Exception as ex:
                logger.error(ex)
                db.session.rollback()
                flash('Cant save post: ' + str(ex))
        else:
            logger.error('Someone have submitted an incorrect form!')
            flash('Invalid form. Please check fields')
    else:
        form = post_form_class()

    return render_template(
        'home.html',
        form=form,
        items=Post.query.all(),
    )
Ejemplo n.º 60
0
    def get(self):
        from auth.models import User
        from page.models import Template
        from wtforms import FormField
        from admin.forms import TemplateBodyFieldForm
        from ext import db
        AddTemplateForm = model_form(Template,db.session,base_class=Form,exclude=['blocks','pages','body'])
        class TemplateForm(AddTemplateForm):
            body = FormField(TemplateBodyFieldForm)

        self._form = TemplateForm
        return self.render()