コード例 #1
0
def detail(post_type=None, slug=None):
    form = None

    if (slug):
        post = Post.objects.get_or_404(slug=slug)

        if (local_settings.context['DEBUG']):
            local_settings.context['debug_msg'] = post.type

        typed_post = post.__class__ if post.__class__ != Post else BlogPost
        post_form = model_form(typed_post, exclude=('created_at', 'slug'))

        if (request.method == 'POST'):
            form = post_form(request.form, initial=post._data)
            if (form.validate()):
                form.populate_obj(post)
                post.save()
                return redirect(url_for('admin.list'))
        else:
            form = post_form(obj=post)
    else:
        typed_post = post_map.get(post_type) if post_type else BlogPost
        post = typed_post()
        post_form = model_form(typed_post, exclude=('created_at', 'slug'))
        form = post_form(request.form)

        if (request.method == 'POST'):
            if (form.validate()):
                form.populate_obj(post)
                post.slug = slugify(post.title)
                post.save()
                return redirect(url_for('admin.list'))

    local_settings.context['form'] = form
    return render_template('admin/detail.html', context=local_settings.context)
コード例 #2
0
ファイル: test_forms.py プロジェクト: fwise/flask-mongoengine
    def test_shared_field_args(self):
        with self.app.test_request_context('/'):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True)
                content = db.StringField(required=False)

            shared_field_args = {
                'title': {
                    'validators': [wtforms.validators.Regexp('test')]
                }
            }

            TitleOnlyForm = model_form(BlogPost,
                                       field_args=shared_field_args,
                                       exclude=['content'])
            BlogPostForm = model_form(BlogPost, field_args=shared_field_args)

            # ensure shared field_args don't create duplicate validators
            title_only_form = TitleOnlyForm()
            self.assertEqual(len(title_only_form.title.validators), 2)

            blog_post_form = BlogPostForm()
            self.assertEqual(len(blog_post_form.title.validators), 2)
コード例 #3
0
    def get_context(self, slug=None):
        """ Create context for template """

        if slug:
            post = Post.objects.get_or_404(slug=slug)
            cls = post.__class__ if post.__class__ != Post else BlogPost
            form_cls = model_form(Post, exclude=('created_at', 'comments'))

            if 'POST' == request.method:
                form = form_cls(request.form, initial=post._data)
            else:
                form = form_cls(obj=post)
        else:
            cls = self.class_map.get(request.args.get('type', 'post'))
            post = cls()
            form_cls = model_form(Post, exclude=('created_at', 'comments'))
            form = form_cls(request.form)

        context = {
            'post': post,
            'form': form,
            'create': slug is None
        }

        return context
コード例 #4
0
    def test_emailfield(self):

        with self.app.test_request_context('/'):
            db = self.db

            class Email(db.Document):
                email = db.EmailField(required=False)

            EmailForm = model_form(Email)
            form = EmailForm(instance=Email())
            self.assertFalse("None" in "%s" % form.email)
            self.assertTrue(form.validate())

            form = EmailForm(MultiDict({"email": ""}))
            self.assertFalse("None" in "%s" % form.email)
            self.assertTrue(form.validate())

            # Ensure required works

            class Email(db.Document):
                email = db.EmailField(required=True)

            EmailForm = model_form(Email)
            form = EmailForm(MultiDict({"email": ""}))
            self.assertFalse("None" in "%s" % form.email)
            self.assertFalse(form.validate())
コード例 #5
0
ファイル: admin.py プロジェクト: Duelist/ianb-flask
def detail(post_type=None,slug=None):
    form = None

    if (slug):
        post = Post.objects.get_or_404(slug=slug)

        if (local_settings.context['DEBUG']):
            local_settings.context['debug_msg'] = post.type

        typed_post = post.__class__ if post.__class__ != Post else BlogPost
        post_form = model_form(typed_post, exclude=('created_at', 'slug'))

        if (request.method == 'POST'):
            form = post_form(request.form, initial=post._data)
            if (form.validate()):
                form.populate_obj(post)
                post.save()
                return redirect(url_for('admin.list'))
        else:
            form = post_form(obj=post)
    else:
        typed_post = post_map.get(post_type) if post_type else BlogPost
        post = typed_post()
        post_form = model_form(typed_post, exclude=('created_at', 'slug'))
        form = post_form(request.form)

        if (request.method == 'POST'):
            if (form.validate()):
                form.populate_obj(post)
                post.slug = slugify(post.title)
                post.save()
                return redirect(url_for('admin.list'))

    local_settings.context['form'] = form
    return render_template('admin/detail.html', context=local_settings.context)
コード例 #6
0
def get_context(id=None):
    if id:
        # edit
        exercise = Exercise.objects.get_or_404(id=id)
        form_cls = model_form(exercise.__class__)

        if request.method == 'POST':
            form = form_cls(request.form, inital=exercise._data)
            # process single line list
            for muscle in filter(None, request.form['muscles'].split('\r\n')):
                form.muscles.append_entry(muscle)
        else:
            form = form_cls(obj=exercise)
    else:
        # create
        exercise = Exercise()
        form_cls = model_form(exercise.__class__)
        form = form_cls(request.form)
        # process single line list
        if 'muscles' in request.form:
            for muscle in filter(None, request.form['muscles'].split('\r\n')):
                form.muscles.append_entry(muscle)

    context = {
            "exercise": exercise,
            "form": form,
            "create": id is None
        }
    return context
コード例 #7
0
ファイル: admin.py プロジェクト: closears/cmsflask
    def _get_context(self, slug=None):

        if slug:
            content = Content.objects.get_or_404(slug=slug)
            # Handle old posts types as well
            cls = content.__class__ if content.__class__ != Content else Post
            form_cls = model_form(cls,  exclude=('created_at', 'modified_at', 'comments', 'slug'))
            if request.method == 'POST':
                form = form_cls(request.form, inital=content._data)
            else:
                form = form_cls(obj=content)
        else:
            # Determine which post type we need
            cls = self.class_map.get(request.args.get('type', 'content'))
            content = cls()
            if isinstance(content, Post):
                form_cls = model_form(cls,  exclude=('created_at', 'modified_at', 'comments', 'slug'))
            elif isinstance(content, Category):
                form_cls = model_form(cls,  exclude=('created_at', 'modified_at', 'slug', 'contents'))
            elif isinstance(content, Comment):
                form_cls = model_form(cls,  exclude=('created_at', 'modified_at'))

            form = form_cls(request.form)
        context = {
            "content": content,
            "form": form,
            "create": slug is None
        }
        return context
コード例 #8
0
ファイル: admin.py プロジェクト: jrrembert/mongo-blog
    def get_context(self, slug=None):

        if slug:
            post = Post.objects.get_or_404(slug=slug)
            # Handle old posts types as well
            cls = post.__class__ if post.__class__ != Post else BlogPost
            form_cls = model_form(cls,  exclude=('created_date', 'comments'))
            if request.method == 'POST':
                form = form_cls(request.form, initial=post._data)
            else:
                form = form_cls(obj=post)
        else:
            # Determine which post type we need
            cls = self.class_map.get(request.args.get('type', 'post'))
            post = cls()
            form_cls = model_form(cls,  exclude=('created_date', 'comments'))
            form = form_cls(request.form)
        
        context = {
            "post": post,
            "form": form,
            "create": slug is None
        }

        return context
コード例 #9
0
    def test_emailfield(self):

        with self.app.test_request_context('/'):
            db = self.db

            class Email(db.Document):
                email = db.EmailField(required=False)

            EmailForm = model_form(Email)
            form = EmailForm(instance=Email())
            self.assertFalse("None" in "%s" % form.email)
            self.assertTrue(form.validate())

            form = EmailForm(MultiDict({"email": ""}))
            self.assertFalse("None" in "%s" % form.email)
            self.assertTrue(form.validate())

            # Ensure required works

            class Email(db.Document):
                email = db.EmailField(required=True)

            EmailForm = model_form(Email)
            form = EmailForm(MultiDict({"email": ""}))
            self.assertFalse("None" in "%s" % form.email)
            self.assertFalse(form.validate())
コード例 #10
0
ファイル: utility.py プロジェクト: nikitph/Ashrm
def poster(request, usr_model_class):
    if request.args.get('id') is None:
        obj_form = model_form(usr_model_class)
        form = obj_form(request.form)
    else:
        mod_obj = usr_model_class.objects(id=str(request.args.get('id'))).first()
        usr_obj_form = model_form(usr_model_class)
        form = usr_obj_form(request.form, mod_obj)

    return str(form.save().id)
コード例 #11
0
ファイル: admin.py プロジェクト: sarlalian/watchmen
 def get_context(self, slug=None):
     if slug:
         event = Event.objects.get_or_404(slug=slug)
         form_cls = model_form(Event, exclude=("created_at", "history"))
         if request.method == "POST":
             form = form_cls(request.form, inital=event._data)
         else:
             form = form_cls(obj=event)
     else:
         event = Event()
         form_cls = model_form(Event, exclude=("created_at", "history"))
         form = form_cls(request.form)
     context = {"event": event, "form": form, "pause": event, "create": slug is None}
     return context
コード例 #12
0
    def test_modelselectfield_multiple_selected_elements_must_be_retained(self):

        db = self.db

        class Dog(db.Document):
            name = db.StringField()
            def __unicode__(self):
                return self.name

        class DogOwner(db.Document):
            dogs = db.ListField(db.ReferenceField(Dog))

        DogOwnerForm = model_form(DogOwner)

        dogs = [Dog(name="fido"), Dog(name="rex")]
        for dog in dogs:
            dog.save()

        dogOwner = DogOwner(dogs=dogs[:1])
        form = DogOwnerForm(obj=dogOwner)
        html = form.dogs()
        import re
        m = re.search("<option selected=.+?>(.*?)</option>", html)
        self.assertIsNotNone(m, "Should have one selected option")
        self.assertEqual( "fido", m.group(1))
コード例 #13
0
    def test_model_form(self):
        db = self.db

        class BlogPost(db.Document):
            title = db.StringField(required=True, max_length=200)
            posted = db.DateTimeField(default=datetime.datetime.now)
            tags = db.ListField(db.StringField(max_length=50))

        class TextPost(BlogPost):
            content = db.StringField(required=True)

        class LinkPost(BlogPost):
            url = db.StringField(required=True)


        # Create a text-based post
        TextPostForm = model_form(TextPost)

        form = TextPostForm(**{
            'title': 'Using MongoEngine',
            'tags': ['mongodb', 'mongoengine']})

        self.assertFalse(form.validate())

        form = TextPostForm(**{
            'title': 'Using MongoEngine',
            'content': 'See the tutorial',
            'tags': ['mongodb', 'mongoengine']})

        self.assertTrue(form.validate())
        form.save()

        self.assertEquals(BlogPost.objects.count(), 1)
コード例 #14
0
ファイル: admin.py プロジェクト: Koboldthegreat/MineZRC
def adminCreatePost():
    if requires_admin():
        backgroundlist = listdir(geturl('static/img/servers'))
        backgroundurl = "/static/img/servers/" + random.choice(backgroundlist)


        PostForm = model_form(Post, exclude=('created_at', 'comments', 'author'))(request.form)

        if request.method == 'POST':
            if PostForm.validate_on_submit():
                print(PostForm.title.data)

                try:
                    post = Post.objects.get(title = PostForm.title.data)
                    PostForm.title.errors.append('Post with this title already exists')
                    return False

                except:
                    user = User.objects.get(mcname = session['usermcname'])
                    post = Post(title = PostForm.title.data, author = user, content = PostForm.content.data, tags = PostForm.tags.data)
                    post.save()
                    flash(u'Successfully created Post: %s. ' % PostForm.title.data, 'success')
                    return redirect(url_for('adminPanel'))

        else:
            return render_template('admin/add_post.html', form = PostForm, create = True, background = backgroundurl)
    else:
        flash('You have to be logged as admin to access this page ', 'warning')
        return redirect('/')
コード例 #15
0
    def post(self, bitbook_id, bitnote_id):
        note, bitbook, unused_bitfields = self.get_context(
            bitbook_id, bitnote_id)
        field_type = request.form['field_type']
        field_title = request.form['field_title']
        if field_type == 'Heading':
            h = request.form['Heading']
            note.title = h
            note.save()
        else:
            field = [x for x in note.bitfields if x.title == field_title][0]
            if field:
                if field_type == 'CommentBox':
                    body = request.form['body']
                    author = User.objects.get_or_404(id=current_user.id)
                    #author = User().save()
                    c = Comment(body=body, author=author)
                    field.comments.append(c)
                elif field_type == 'Link':
                    if request.form['link']:
                        link = request.form['link']
                        field.link = link

                        s = summary.Summary(link)
                        s.extract()
                        if s.url:
                            field.og_url = s.url
                        if s.title:
                            field.og_title = s.title
                        if s.image:
                            field.og_image = s.image.url
                        if s.description:
                            field.og_description = s.description

                        # l = opengraph.OpenGraph(url=link)
                        # if l.is_valid():
                        # 	field.og_url = l.url
                        # 	field.og_title = l.title
                        # 	field.og_type = l.type
                        # 	field.og_image = l.image
                        # 	if 'description' in l.keys():
                        # 		field.og_description = l.description
                elif field_type == 'Location':
                    geolocator = Nominatim()
                    a = request.form['address']
                    l = geolocator.geocode(a)
                    field.location = [l.latitude, l.longitude]
                    field.addr = l.address
                else:
                    constructor = globals()[field_type]
                    mform = model_form(constructor,
                                       exclude=['created_at', 'title'])
                    form = mform(request.form)
                    form.populate_obj(field)
                note.save()

        return render_template('notes/note.html',
                               note=note,
                               bitbook=bitbook,
                               unused_bitfields=unused_bitfields)
コード例 #16
0
ファイル: views.py プロジェクト: shea256/headerfile.me
    def post(self, username):
        form_cls = model_form(User, exclude=('created_at', 'websites', 'work','email','password','username'))
        context = self.get_context(form_cls, username)
        form = context.get('form')

        error = None
        if form.validate():
            user = context.get('user')
            form.populate_obj(user)

            if 'industries' in form:
                industries = request.form.getlist('industries')
                user.industries = json.dumps(industries)
            if 'technologies' in form:
                technologies = request.form.getlist('technologies')
                user.technologies = json.dumps(technologies)

            self.remove_empty_data_from_form(form, 'github', user)
            self.remove_empty_data_from_form(form, 'blog', user)
            self.remove_empty_data_from_form(form, 'facebook', user)
            self.remove_empty_data_from_form(form, 'twitter', user)
            self.remove_empty_data_from_form(form, 'linkedin', user)
            self.remove_empty_data_from_form(form, 'stackoverflow', user)
            self.remove_empty_data_from_form(form, 'topcoder', user)

            user.save()
            return redirect(url_for('users.details', username=username))
        return render_template('users/edit.html', error=error, **context)
コード例 #17
0
class AddView(MethodView):

    form = model_form(Card, exclude=['created_at'])

    def get_context(self):
        form = self.form(request.form)

        context = {"form": form}
        return context

    def get(self):
        context = self.get_context()
        return render_template('cards/add.html', **context)

    def post(self):
        context = self.get_context()
        form = context.get('form')

        if form.validate():
            card = Card()
            form.populate_obj(card)

            card.save()

            cards = Card.objects.all()
            return redirect(url_for('cards.list', cards=cards))

        return render_template('cards/add.html', **context)
コード例 #18
0
def show_content(page=1):
    page = int(page)
    RssResultsForm = model_form(RssResults)
    form = RssResultsForm()
    pagination = RssResults.objects.paginate(page=page, per_page=10, error_out=False)
    rssinfos = pagination.items
    return render_template('rss_show_content.html', rssinfos=rssinfos, pagination=pagination, form=form)
コード例 #19
0
ファイル: admin.py プロジェクト: Koboldthegreat/MineZRC
def adminEditPost(title):
    print(title)
    if requires_admin():
        try:
            post = Post.objects.get(title = title)
            backgroundlist = listdir(geturl('static/img/servers'))
            backgroundurl = "/static/img/servers/" + random.choice(backgroundlist)
            PostForm = model_form(Post, exclude=('created_at', 'comments', 'author'))(request.form)
            if request.method == 'POST':
                if True:
                    if PostForm.title.data:
                        post.update(title = PostForm.title.data)
                        title = PostForm.title.data
                    if PostForm.content.data:
                        post.update(content = PostForm.content.data)
                    if PostForm.tags.data:
                        post.update(tags = PostForm.tags.data)


                    flash(u'Successfully edited Post: %s. ' % title, 'success')
                return redirect(url_for('adminPanel'))

            else:
                return render_template('admin/edit_post.html', form = PostForm, post = post, create = True, background = backgroundurl)
        except:
            flash(u"Post doesn't exist!", 'danger')
        return redirect(url_for('adminPanel'))
    else:
        flash('You have to be logged as admin to access this page ', 'warning')
        return redirect('/')
コード例 #20
0
ファイル: test_forms.py プロジェクト: fwise/flask-mongoengine
    def test_sub_field_args(self):
        with self.app.test_request_context('/'):
            db = self.db

            class TestModel(db.Document):
                lst = db.ListField(db.StringField())

            field_args = {
                'lst': {
                    'label': 'Custom Label',
                    'field_args': {
                        'widget': wtforms.widgets.HiddenInput(),
                        'label': "Hidden Input"
                    }
                }
            }
            CustomForm = model_form(TestModel, field_args=field_args)

            custom_form = CustomForm(obj=TestModel(lst=["Foo"]))
            list_label = flask.render_template_string(
                "{{ custom_form.lst.label }}", custom_form=custom_form)
            self.assertTrue("Custom Label" in list_label)
            self.assertTrue("Hidden Input" not in list_label)

            sub_label = flask.render_template_string("{{ custom_form.lst }}",
                                                     custom_form=custom_form)
            self.assertTrue("Hidden Input" in sub_label)
コード例 #21
0
ファイル: routes.py プロジェクト: publicscience/brain
class ConfigAPI(MethodView):
    form = model_form(Config, exclude=['created_at'])

    @requires_auth
    def get(self):
        config = Config.objects[0]
        form = self.form(request.form, obj=config)
        return render_template('config/index.html', config=config, form=form)

    def post(self):
        config = Config.objects[0]
        form = self.form(request.form, obj=config)

        if form.validate():
            form.populate_obj(config)

            # Need to reload the brain.
            if form.ramble.data != brain.MKV.ramble or form.spasm.data != brain.MKV.spasm:
                logger.info('Brain config value changed!')
                brain.MKV.ramble = form.ramble.data
                brain.MKV.spasm = form.spasm.data

            # If the ngram size has changed,
            # the brain needs to be retrained.
            if form.ngram_size.data != brain.MKV.n:
                logger.info('Brain ngram size changed! Retraining...')
                brain.MKV.n = form.ngram_size.data
                brain.retrain()

            config.save()
            flash('I will change my ways.')
            return redirect(url_for('config_api'))

        return redirect(url_for('config_api'))
コード例 #22
0
    def test_modelselectfield(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            DogOwnerForm = model_form(DogOwner)

            dog = Dog(name="fido")
            dog.save()

            form = DogOwnerForm(dog=dog)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dog.widget))
            self.assertFalse(form.dog.widget.multiple)

            # Validate selecting one item
            form = DogOwnerForm(MultiDict({
                'dog': dog.id,
                }))
            self.assertEqual(form.dog.data, dog)

            # Validate selecting no item
            form = DogOwnerForm(MultiDict({
                'dog': u'__None',
                }), dog=dog)
            self.assertEqual(form.dog.data, None)
コード例 #23
0
def admin_categories():
    action = request.args.get('action', '')
    oid = request.args.get('id', '')

    if action == 'remove':
        sentenced = OlympiadCategory.objects.get(id=oid)
        sentenced.delete()
        sentenced.save()

    elif action == 'edit':
        edited = OlympiadCategory.objects.get(id=oid)
        print(edited.id)
        print(edited.url)
        OlympiadCategoryForm = model_form(OlympiadCategory)
        form = OlympiadCategoryForm(request.form,
                                    obj=edited,
                                    csrf_enabled=False)
        if form.validate_on_submit():
            form.populate_obj(edited)
            edited.save()
            print(edited.id)
            print(edited.url)
            url = request.form['callback_url']
            return redirect(url)
        return render_template('admin/categories_edit.html',
                               form=form,
                               oid=oid)

    return render_template('admin/categories.html',
                           categories=OlympiadCategory.objects)
コード例 #24
0
class DetailView(MethodView):

    form = model_form(Resource, exclude=['created_at'])

    def get_context(self, slug):
        room = Room.objects.get_or_404(slug=slug)
        form = self.form(request.form)

        context = {'room': room, 'form': form}
        return context

    def get(self, slug):
        context = self.get_context(slug)
        return render_template('rooms/detail.html', **context)

    def post(self, slug):
        context = self.get_context(slug)
        form = context.get('form')

        if form.validate():
            resource = Resource()
            form.populate_obj(resource)

            resource = context.get('resource')
            room.resources.append(resource)
            room.save()

            return redirect(url_for('rooms.detail', slug=slug))

        return render_template('rooms/detail.html', **context)
コード例 #25
0
ファイル: admin.py プロジェクト: ixxra/olympiad-flask
def admin_categories():
    action = request.args.get('action', '')
    oid = request.args.get('id', '')

    if action == 'remove':
        sentenced = OlympiadCategory.objects.get(id=oid)
        sentenced.delete()
        sentenced.save()

    elif action == 'edit':
        edited = OlympiadCategory.objects.get(id=oid)
        print (edited.id)
        print (edited.url)
        OlympiadCategoryForm = model_form(OlympiadCategory)
        form = OlympiadCategoryForm(request.form, obj=edited, csrf_enabled=False)
        if form.validate_on_submit():
            form.populate_obj(edited)
            edited.save()
            print (edited.id)
            print (edited.url)
            url = request.form['callback_url']
            return redirect(url)
        return render_template('admin/categories_edit.html', form=form, oid=oid)

    return render_template('admin/categories.html', categories=OlympiadCategory.objects)
コード例 #26
0
class EditPost(MethodView):
    form = model_form(Post, 
        exclude=('created_at', 'comments', 'updated_at'))

    def get(self, slug):
        post = Post.objects.get_or_404(slug=slug)
        form = self.form()
        return render_template('edit.html', post=post, form=form)

    def post(self, slug):
        post = Post.objects.get_or_404(slug=slug)
        form = self.form(request.form)
        tags = request.form['tags'] if request.form['tags'] else ''

        if form.validate():
            now = datetime.now()

            for field in ['slug', 'title', 'body']:
                post[field] = form[field].data

            tags = uniq_list(tags, ',')
            post['tags'] = tags

            post['updated_at'] = now

            post.save()

        return redirect(url_for('.index'))
コード例 #27
0
    def test_modelselectfield_multiple(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            dogs = [Dog(name="fido"), Dog(name="rex")]
            for dog in dogs:
                dog.save()

            form = DogOwnerForm(dogs=dogs)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dogs.widget))
            self.assertEqual(True, form.dogs.widget.multiple)

            # Validate if both dogs are selected
            choices = list(form.dogs)
            self.assertEqual(len(choices), 2)
            self.assertTrue(choices[0].checked)
            self.assertTrue(choices[1].checked)
コード例 #28
0
ファイル: admin.py プロジェクト: alexmayn/webapps
    def get_context(self, slug=None):
        """
            This is method get post-form and post objects

            :param slug: The _id user
            :type slug: Str

        """
        form_cls = model_form(Post, exclude=('created_at', 'comments'))

        if slug:
            post = Post.objects.get_or_404(slug=slug)
            if request.method == 'POST':
                form = form_cls(request.form, inital=post._data)
            else:
                form = form_cls(obj=post)
        else:
            post = Post()
            form = form_cls(request.form)

        context = {
            "post": post,
            "form": form,
            "create": slug is None
        }
        return context
コード例 #29
0
    def test_modelselectfield_multiple_initalvalue_None(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            dogs = [Dog(name="fido"), Dog(name="rex")]
            for dog in dogs:
                dog.save()

            form = DogOwnerForm(dogs=None)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dogs.widget))
            self.assertEqual(True, form.dogs.widget.multiple)

            # Validate if both dogs are selected
            choices = list(form.dogs)
            self.assertEqual(len(choices), 2)
            self.assertFalse(choices[0].checked)
            self.assertFalse(choices[1].checked)
コード例 #30
0
	def get_context(self, slug=None):
	
		form_cls = model_form(RecipeInDatabase, exclude=('created_at', 'author', 'slug', 'comments'))
		#form2_cls = model_form(Ingredient)

		if slug:
			recipe = RecipeInDatabase.objects.get_or_404(slug=slug)
			#ingredient = recipe.ingredients
			if request.method == 'POST':
				form = form_cls(request.form, initial=recipe._data)
				#form2 = form2_cls(request.form, initial=ingredient._data)
			else:
				form = form_cls(obj=recipe)
				#form2 = form2_cls(obj=ingredient)
		else:
			recipe = RecipeInDatabase()
			#ingredient = Ingredient()
			form = form_cls(request.form)
			#form2 = form2_cls(request.form)

		context = {
			"recipe": recipe,
			#"ingredients": ingredient,
			"form": form,
			#"form2": form2,
			"create": slug is None
		}
		return context
コード例 #31
0
    def test_model_form_with_custom_query_set(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                breed = db.StringField()

                @queryset_manager
                def large_objects(cls, queryset):
                    return queryset(breed__in=['german sheppard', 'wolfhound'])

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            big_dogs = [Dog(breed="german sheppard"), Dog(breed="wolfhound")]
            dogs = [Dog(breed="poodle")] + big_dogs
            for dog in dogs:
                dog.save()

            BigDogForm = model_form(
                DogOwner, field_args={'dog': {
                    'queryset': Dog.large_objects
                }})

            form = BigDogForm(dog=big_dogs[0])
            self.assertTrue(form.validate())
            self.assertEqual(big_dogs, [d[1] for d in form.dog.iter_choices()])
コード例 #32
0
ファイル: views.py プロジェクト: zming619/quokka
class CommentView(MethodView):

    form = model_form(
        Comment,
        only=['author_name', 'author_email', 'body']
    )

    @staticmethod
    def render_context(path, form):
        comments = Comment.objects(path=path, published=True)
        return render_template('content/comments.html',
                               comments=comments,
                               form=form,
                               path=path)

    def get(self, path):
        return self.render_context(path, form=self.form())

    def post(self, path):
        form = self.form(request.form)

        if form.validate():
            comment = Comment(path=path)
            form.populate_obj(comment)
            if current_user.is_authenticated():
                comment.published = True
                comment.author_name = current_user.name
                comment.author_email = current_user.email
            comment.save()
            return self.render_context(path, form=self.form())

        return self.render_context(path, form=form)
コード例 #33
0
    def test_modelselectfield_multiple_selected_elements_must_be_retained(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

                def __unicode__(self):
                    return self.name

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            fido = Dog(name="fido").save()
            Dog(name="rex").save()

            dogOwner = DogOwner(dogs=[fido])
            form = DogOwnerForm(obj=dogOwner)
            html = form.dogs()

            m = re.search("<option selected .+?>(.*?)</option>", html)
            self.assertTrue(m is not None, "Should have one selected option")
            self.assertEqual("fido", m.group(1))
コード例 #34
0
class DetailView(MethodView):

    form = model_form(Review, exclude=['created_at'])

    def get_context(self, slug):
        product = Product.objects.get_or_404(slug=slug)
        form = self.form(request.form)

        context = {
            "product": product,
            "form": form
        }
        return context

    def get(self, slug):
        context = self.get_context(slug)
        return render_template('products/detail.html', **context)

    def post(self, slug):
        context = self.get_context(slug)
        form = context.get('form')

        if form.validate():
            review = Review()
            form.populate_obj(review)

            product = context.get('product')
            product.reviews.append(review)
            product.save()

            return redirect(url_for('products.detail', slug=slug))
        return render_template('products/detail.html', **context)
コード例 #35
0
    def test_modelselectfield_multiple_selected_elements_must_be_retained(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

                def __unicode__(self):
                    return self.name

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            fido = Dog(name="fido").save()
            Dog(name="rex").save()

            dogOwner = DogOwner(dogs=[fido])
            form = DogOwnerForm(obj=dogOwner)
            html = form.dogs()

            m = re.search("<option selected .+?>(.*?)</option>", html)
            self.assertTrue(m is not None, "Should have one selected option")
            self.assertEqual("fido", m.group(1))
コード例 #36
0
    def test_modelselectfield(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            DogOwnerForm = model_form(DogOwner)

            dog = Dog(name="fido")
            dog.save()

            form = DogOwnerForm(dog=dog)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dog.widget))
            self.assertFalse(form.dog.widget.multiple)

            # Validate selecting one item
            form = DogOwnerForm(MultiDict({
                'dog': dog.id,
                }))
            self.assertEqual(form.dog.data, dog)

            # Validate selecting no item
            form = DogOwnerForm(MultiDict({
                'dog': u'__None',
                }), dog=dog)
            self.assertEqual(form.dog.data, None)
コード例 #37
0
class DetailView(MethodView):

    form = model_form(Comment, exclude=['created_at'])

    def get_context(self, slug):
        post = Post.objects.get_or_404(slug=slug)
        form = self.form(request.form)

        context = {"post": post, "form": form}
        return context

    def get(self, slug):
        context = self.get_context(slug)
        return render_template('posts/detail.html', **context)

    def post(self, slug):
        context = self.get_context(slug)
        form = context.get('form')

        if form.validate():
            comment = Comment()
            form.populate_obj(comment)

            post = context.get('post')
            post.comments.append(comment)
            post.save()

            return redirect(url_for('posts.detail', slug=slug))
        return render_template('posts/detail.html', **context)
コード例 #38
0
    def get_context(self, slug=None):

        if slug:
            post = Post.objects.get_or_404(slug=slug)
            cls = post.__class__ if post.__class__ != Post else BlogPost
            form_cls = model_form(cls, exclude=('created_at', 'comments'))
            if request.method == 'POST':
                form = form_cls(request.form, inital=post._data)
            else:
                form = form_cls(obj=post)
        else:
            cls = self.class_map.get(request.args.get('type', 'post'))
            post = cls()
            form_cls = model_form(cls, exclude=('created_at', 'comments'))
            form = form_cls(request.form)
        context = {"post": post, "form": form, "create": slug is None}
        return context
コード例 #39
0
ファイル: generic.py プロジェクト: carriercomm/yeti
 def edit(self, id):
     if request.method == "POST":
         return self.handle_form(id=id)
     obj = self.klass.objects.get(id=id)
     form = model_form(obj.__class__, exclude=obj.__class__.exclude_fields)(obj=obj)
     return render_template(
         "{}/edit.html".format(self.klass.__name__.lower()), form=form, obj_type=self.klass.__name__, obj=obj
     )
コード例 #40
0
ファイル: generic.py プロジェクト: carriercomm/yeti
    def handle_form(self, id=None, klass=None):
        if klass:  # create
            obj = klass()
            form = model_form(klass, exclude=klass.exclude_fields)(request.form)
        else:  # update
            obj = self.klass.objects.get(id=id)
            klass = obj.__class__
            form = model_form(klass, exclude=klass.exclude_fields)(request.form, initial=obj._data)

        if form.validate():
            form.populate_obj(obj)
            obj.save()
            return redirect(url_for("frontend.{}:get".format(self.__class__.__name__), id=obj.id))
        else:
            return render_template(
                "{}/edit.html".format(self.klass.__name__.lower()), form=form, obj_type=klass.__name__, obj=obj
            )
コード例 #41
0
ファイル: admin.py プロジェクト: cyrilnigg/ingestr
 def get_context(self, slug=None):
     form_cls = model_form(Case, exclude=['created_at'])
     if slug:
         case = Case.objects.get_or_404(slug=slug)
         if request.method == 'POST':
             form = form_cls(request.form, inital=case._data)
         else:
             form = form_cls(obj=case)
コード例 #42
0
    def test_passwordfield(self):
        db = self.db
        class User(db.Document):
            password = db.StringField()

        UserForm = model_form(User, field_args = { 'password': {'password' : True} })
        form = UserForm(password='******')
        self.assertEqual(wtforms.widgets.PasswordInput, type(form.password.widget))
コード例 #43
0
ファイル: views.py プロジェクト: makeclan/quokka
class ContentDetail(MethodView):
    form = model_form(
        Comment,
        exclude=['created_at', 'created_by', 'published']
    )

    def get_context(self, long_slug):
        now = datetime.now()
        homepage = Channel.objects.get(is_homepage=True)

        if long_slug.startswith(homepage.slug) and \
                len(long_slug.split('/')) < 3:
            slug = long_slug.split('/')[-1]
            return redirect(url_for('detail', long_slug=slug))

        try:
            content = Content.objects.get(
                long_slug=long_slug,
                published=True,
                available_at__lte=now
            )
        except Content.DoesNotExist:
            content = Content.objects.get_or_404(
                channel=homepage,
                slug=long_slug,
                available_at__lte=now,
                published=True
            )

        form = self.form(request.form)

        context = {
            "content": content,
            "form": form
        }
        return context

    def get(self, long_slug):
        context = self.get_context(long_slug)
        if isinstance(context, collections.Callable):
            return context
        return render_template('content/detail.html', **context)

    def post(self, long_slug):
        context = self.get_context(long_slug)
        form = context.get('form')

        if form.validate():
            comment = Comment()
            form.populate_obj(comment)

            content = context.get('content')
            content.comments.append(comment)
            content.save()

            return redirect(url_for('.detail', long_slug=long_slug))

        return render_template('content/detail.html', **context)
コード例 #44
0
ファイル: admin.py プロジェクト: ixxra/olympiad-flask
def create_category():
    OlympiadCategoryForm = model_form(OlympiadCategory)
    form = OlympiadCategoryForm(request.form, csrf_enabled=False)
    if form.validate_on_submit():
        form.save()
        url = request.form['callback_url']
        #url_for('categories')
        return redirect(url)
    return render_template('admin/categories_new.html', form=form)
コード例 #45
0
def create_category():
    OlympiadCategoryForm = model_form(OlympiadCategory)
    form = OlympiadCategoryForm(request.form, csrf_enabled=False)
    if form.validate_on_submit():
        form.save()
        url = request.form['callback_url']
        #url_for('categories')
        return redirect(url)
    return render_template('admin/categories_new.html', form=form)
コード例 #46
0
ファイル: utility.py プロジェクト: nikitph/Ashrm
def cruder(req, usr_model_class, template, route_name, display_name, field_args=None, list_args=None,
           key_id='', cache_class=''):
    mode = get_mode(req)
    # 1 = c, 2= r, 3=u, 4=d, 5=l

    if mode == 1:
        print(1)
        usr_obj_form = model_form(usr_model_class, field_args=field_args)
        print(2)
        form = usr_obj_form(req.form)
        print(form)
        return render_template(template, form=form, mode=1, routename=route_name, displayname=display_name,
                               key_id=key_id, cache_class=cache_class)

    elif mode == 2:
        mod_obj = usr_model_class.objects(id=req.args.get('id')).first()
        usr_obj_form = model_form(usr_model_class, field_args=field_args)
        form = usr_obj_form(req.form, mod_obj)
        return render_template(template, form=form, mode=2, routename=route_name, displayname=display_name,
                               key_id=key_id)

    elif mode == 3:
        mod_obj = usr_model_class.objects(id=req.args.get('id')).first()
        usr_obj_form = model_form(usr_model_class, field_args=field_args)
        form = usr_obj_form(req.form, mod_obj)
        return render_template(template, form=form, mode=3, routename=route_name, displayname=display_name,
                               key_id=key_id, cache_class=cache_class)

    elif mode == 4:
        mod_obj = usr_model_class.objects(id=req.args.get('id')).first()
        mod_obj.delete()
        return render_template(template, mode=4, routename=route_name, displayname=display_name, key_id=key_id)

    elif mode == 5:
        mod_obj = model_form(usr_model_class, field_args=list_args)
        form = mod_obj(req.form)
        return render_template(route_name + 'list.html',
                               msg=usr_model_class.objects(school=str(g.user.schoolid)).to_json(), form=form,
                               routename=route_name, displayname=display_name, key_id=key_id)

    else:
        usr_obj_form = model_form(usr_model_class, field_args=field_args)
        form = usr_obj_form(req.form)
        return render_template(template, form=form, mode=1, routename=route_name, displayname=display_name)
コード例 #47
0
ファイル: generic.py プロジェクト: carriercomm/yeti
 def new(self, klass=None):
     if not klass:
         klass = self.klass
     if request.method == "POST":
         return self.handle_form(klass=klass)
     form = model_form(klass, exclude=klass.exclude_fields)()
     obj = None
     return render_template(
         "{}/edit.html".format(self.klass.__name__.lower()), form=form, obj_type=klass.__name__, obj=obj
     )
コード例 #48
0
    def get_context(self, slug=None):

        if slug:
            post = Post.objects.get_or_404(slug=slug)
            # Seta o tipo de post default - soh escrita
            cls = post.__class__ if post.__class__ != Post else BlogPost
            form_cls = model_form(cls, exclude=('created_at', 'comments'))
            if request.method == 'POST':
                form = form_cls(request.form, inital=post._data)
            else:
                form = form_cls(obj=post)
        else:
            # Determina o tipo de post diferente - video, imagem, quote, etc.
            cls = self.class_map.get(request.args.get('type', 'post'))
            post = cls()
            form_cls = model_form(cls, exclude=('created_at', 'comments'))
            form = form_cls(request.form)
        context = {"post": post, "form": form, "create": slug is None}
        return context
コード例 #49
0
ファイル: admin.py プロジェクト: ramaprv/digi-mart-flask
    def get_context(self, slug=None):

        if slug:
            product = Product.objects.get_or_404(slug=slug)
            # Handle old posts types as well
            cls = product.__class__ if product.__class__ != Product else Product
            form_cls = model_form(cls, exclude=('created_at', 'reviews'))
            if request.method == 'POST':
                form = form_cls(request.form, inital=product._data)
            else:
                form = form_cls(obj=product)
        else:
            # Determine which post type we need
            cls = self.class_map.get(request.args.get('type', 'product'))
            product = cls()
            form_cls = model_form(cls, exclude=('created_at', 'reviews'))
            form = form_cls(request.form)
        context = {"product": product, "form": form, "create": slug is None}
        return context
コード例 #50
0
ファイル: view.py プロジェクト: andrealmar/flask-admin
 def conv_EmbeddedDocument(self, model, field, kwargs):
     kwargs = {
         'validators': [],
         'filters': [],
     }
     form_class = model_form(field.document_type_obj, base_class=AdminModelForm, converter=self.__class__(), field_args={})
     def get_form_class(*args, **kwargs):
         kwargs['csrf_enabled'] = False
         return form_class(*args, **kwargs)
     return wtf.FormField(get_form_class, **kwargs)
コード例 #51
0
    def test_passwordfield(self):
        with self.app.test_request_context('/'):
            db = self.db

            class User(db.Document):
                password = db.StringField()

            UserForm = model_form(User, field_args={'password': {'password': True}})
            form = UserForm(password='******')
            self.assertEqual(wtforms.widgets.PasswordInput, type(form.password.widget))
コード例 #52
0
    def test_passwordfield(self):
        with self.app.test_request_context("/"):
            db = self.db

            class User(db.Document):
                password = db.StringField()

            UserForm = model_form(User, field_args={"password": {"password": True}})
            form = UserForm(password="******")
            self.assertEqual(wtforms.widgets.PasswordInput, type(form.password.widget))
コード例 #53
0
ファイル: views.py プロジェクト: bopopescu/LeagueMgr
class LeagueManagePage(MethodView):
    form = model_form(Participant, exclude=['created_at', 'slug'])

    def get(self, slug):
        league = League.objects.get_or_404(slug=slug)

        participant_form = self.form(request.form)
        return render_template('leagues/league_manage.html',
                               league=league,
                               participant_form=participant_form,
                               slug=slug)
コード例 #54
0
ファイル: api.py プロジェクト: Jeff-Lewis/balanced-notify
    def post(self):
        form_cls = model_form(Notification)
        notification = Notification()
        form = form_cls(request.form, csrf_enabled=False)
        if not form.validate():
            return json.dumps(form.errors, default=json_util.default), 400

        form.populate_obj(notification)
        notification.save()
        data = [dict(message=notification.message, id='%s' % notification.pk)]
        return json.dumps({'data': data}, default=json_util.default), 201
コード例 #55
0
    def get_context(self, permalink=None):

        if permalink:
            post = Post.objects.get_or_404(permalink=permalink)
            #print(post.__class__)
            # Handle old posts types as well
            cls = post.__class__
            form_cls = model_form(cls, exclude=('created', 'comments'))
            if request.method == 'POST':
                form = form_cls(request.form, inital=post._data)
            else:
                form = form_cls(obj=post)
        else:
            # Determine which post type we need
            cls = self.class_map.get(request.args.get('type', 'post'))
            post = cls()
            form_cls = model_form(cls, exclude=('created', 'comments'))
            form = form_cls(request.form)
        context = {"post": post, "form": form, "create": permalink is None}
        return context
コード例 #56
0
    def test_model_form_only(self):
        with self.app.test_request_context('/'):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True, max_length=200)
                posted = db.DateTimeField(default=datetime.datetime.now)
                tags = db.ListField(db.StringField())

            BlogPost.drop_collection()

            BlogPostForm = model_form(BlogPost, only=['tags'])
            form = BlogPostForm()
            self.assertTrue(hasattr(form, 'tags'))
            self.assertFalse(hasattr(form, 'posted'))

            BlogPostForm = model_form(BlogPost, exclude=['posted'])
            form = BlogPostForm()
            self.assertTrue(hasattr(form, 'tags'))
            self.assertFalse(hasattr(form, 'posted'))
コード例 #57
0
    def test_model_form_only(self):
        with self.app.test_request_context('/'):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True, max_length=200)
                posted = db.DateTimeField(default=datetime.datetime.now)
                tags = db.ListField(db.StringField())

            BlogPost.drop_collection()

            BlogPostForm = model_form(BlogPost, only=['tags'])
            form = BlogPostForm()
            self.assertTrue(hasattr(form, 'tags'))
            self.assertFalse(hasattr(form, 'posted'))

            BlogPostForm = model_form(BlogPost, exclude=['posted'])
            form = BlogPostForm()
            self.assertTrue(hasattr(form, 'tags'))
            self.assertFalse(hasattr(form, 'posted'))
コード例 #58
0
ファイル: views.py プロジェクト: VertigoStr/flask-oilbase
class ContactsPage(MethodView):

    form = model_form(CallBack,
                      field_args={
                          'name': {
                              'description': "Ваше имя"
                          },
                          'email': {
                              'description': "Ваш почтовый адрес"
                          },
                          'phone': {
                              'description': "Ваш телефон"
                          },
                          'message': {
                              'description': "Ваше сообщение"
                          },
                      })

    def get_context(self):
        contacts = Contacts.objects.all()
        departs = Departaments.objects.all()
        departaments = Departaments.objects(title=u"Администрация").get()
        main_persons = departaments['personal']
        departaments = Departaments.objects(title=u"Центр поставок").get()
        send_persons = departaments['personal']
        form = self.form(request.form)

        context = {
            "form": form,
            "contacts": contacts,
            "departs": departs,
            "main_persons": main_persons,
            "send_persons": send_persons
        }

        return context

    def get(self):
        context = self.get_context()
        return render_template('oilsite/contacts.html', **context)

    def post(self):
        context = self.get_context()
        form = context.get('form')

        if form.validate():
            callback = CallBack()
            form.populate_obj(callback)
            callback.save()

            return redirect(url_for('oilsite.contacts'))

        return render_template('oilsite/contacts.html', **context)
コード例 #59
0
    def test_binaryfield(self):

        with self.app.test_request_context('/'):
            db = self.db

            class Binary(db.Document):
                binary = db.BinaryField()

            BinaryForm = model_form(Binary)
            form = BinaryForm(MultiDict({'binary': '1'}))
            self.assertTrue(form.validate())
            form.save()