class TextEditForm(Form):
    content = TextField('Content', validators=[DataRequired()]) class LongTextEditForm(Form):
    content = TextAreaField('Content', validators=[DataRequired()]) class DateEditForm(Form):
    content = DateField('Date', format='%d %b %Y', validators=[
        DataRequired()]) class TimeEditForm(Form):
    content = TimeField('Time', validators=[DataRequired()]) class ImageEditForm(Form):
    image = FileField('Image', validators=[
        DataRequired(),
        FileAllowed(
            ('gif', 'jpg', 'jpeg', 'png'),
            ('Only image files (gif, jpg, png) can be uploaded '
                'for this field'))]) class ReorderForm(Form):
    items = FieldList(FormField(ReorderItemForm)) def get_model_class(model_classpath, model_name):
    """Dynamically imports the model with the specified classpath."""

    model_classpath_format = r'^[a-z0-9_]+(\.[A-Za-z0-9_]+)+$'

    if not re.match(model_classpath_format, model_classpath):
        raise ValueError(
            ('Class path "%s" for model name "%s" '
                'must be a valid Python module / class path (in the '
                'format "%s")') % (
                    model_classpath,
                    model_name,
                    model_classpath_format))

    model_classpath_split = model_classpath.rpartition('.')
    model_modulepath, model_classname = (
        model_classpath_split[0],
        model_classpath_split[2])

    try:
        model_module = importlib.import_module(model_modulepath)
    except ImportError:
        raise ValueError(
            ('Error importing module "%s" for '
                'model name "%s"') % (
                    model_modulepath,
                    model_name))

    model_class = getattr(model_module, model_classname, None)
    if not model_class:
        raise ValueError(
            ('Class "%s" not found in module "%s" for '
                'model name "%s"') % (
                    model_classname,
                    model_modulepath,
                    model_name))

    return model_class def placeholder_or_random_sample_image():
    """
    Gets a random sample image if possible, otherwise the default
    placeholder image.
    """

    is_sample_images_configured = (
        app.config.get('EDITABLE_SAMPLE_IMAGES_SCRAPE_URL') and
        app.config.get('EDITABLE_SAMPLE_IMAGES_RELATIVE_PATH'))

    return (is_sample_images_configured
            and random_sample_image()
            or app.config['EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH']) def placeholder_or_random_sample_text():
    """
    Gets a random sample chunk of text if possible, otherwise the
    default placeholder text.
    """

    is_sample_text_configured = (
        app.config.get('EDITABLE_SAMPLE_TEXT_SCRAPE_URLS') and
        True or False)

    return (is_sample_text_configured
            and random_sample_text()
            or app.config['EDITABLE_PLACEHOLDER_TEXT'])
from datetime import datetime
from glob import glob
from operator import itemgetter
from sqlalchemy.exc import IntegrityError
from flask import current_app as app
from flask import (abort, Blueprint, flash, url_for, redirect, request,
                   session, Response)
from flask_login import login_required, current_user
from flask_transfer import Transfer
from werkzeug import secure_filename
from flask_wtf import Form
from flask_editablesite.extensions import db
from flask_editablesite.editable.forms import (
    TextEditForm, LongTextEditForm, DateEditForm, TimeEditForm,
    ImageEditForm, ReorderForm)
from flask_editablesite.editable.utils import get_model_class
from flask_editablesite.editable.sample_images import (
    placeholder_or_random_sample_image,)
from flask_editablesite.editable.sample_text import (
    placeholder_or_random_sample_text,)
from flask_editablesite.utils import flash_errors
import os

    if form.validate_on_submit():
        content = form.content.data

        ret = update_submit_handler(
            model_name=model_name,
            model_identifier=model_identifier,
            model_identifier_int=model_identifier_int,
            title_field_name=title_field_name,
            content=content,
            model=model,
            field_name=field_name,
            is_autosave=is_autosave)

        if ret:
            return ret
    else:
        if is_autosave:
            return Response('ERROR', 400)
        else:
            flash_errors(form)

    return redirect(url_for("public.home"))


@blueprint.route(
    "/text-update/<model_name>/<field_name>/<model_identifier>/",
    methods=["POST"])
@login_required
def text_update(model_name, field_name, model_identifier):
    return text_update_func(
        model_name=model_name,
        field_name=field_name,
        model_identifier=model_identifier)


@blueprint.route(
    "/text-update-autosave/<model_name>/<field_name>/<model_identifier>/",
    methods=["POST"])
@login_required
def text_update_autosave(model_name, field_name, model_identifier):
    return text_update_func(
        model_name=model_name,
        field_name=field_name,
        model_identifier=model_identifier,
        is_autosave=True)


def date_update_func(model_name, field_name, model_identifier,
                     is_autosave=False):
    try:
        v = app.config['EDITABLE_MODELS'][model_name]
    except KeyError:
        abort(404)

    if not(('date_fields' in v) and (field_name in v['date_fields'])):
        abort(404)

    try:
        model_classpath = v['classpath']
    except KeyError:
        raise ValueError((
            'No class path defined in app config\'s '
            'EDITABLE_MODELS for model name "{0}"').format(
                model_name))

    try:
        identifier_field_name = v['identifier_field']
    except KeyError:
        raise ValueError((
            'No identifier field defined in app '
            'config\'s EDITABLE_MODELS for model name "{0}"').format(
                model_name))

    try:
        title_field_name = v['title_field']
    except KeyError:
        raise ValueError((
            'No title field defined in app '
            'config\'s EDITABLE_MODELS for model name "{0}"').format(
                model_name))

    model_class = get_model_class(model_classpath, model_name)

    try:
        model_identifier_int = int(model_identifier)
    except ValueError:
        model_identifier_int = None

    filter_by_kwargs = {
        identifier_field_name: model_identifier,
        'active': True}
    model = None

    if app.config.get('USE_SESSIONSTORE_NOT_DB'):
        model_store = session.get(model_name, None)
        model_dict = None

        if model_store and (type(model_store).__name__ == 'list'):
            try:
                model_dict = model_store[model_identifier_int]
            except KeyError:
                pass
        elif model_store and (type(model_store).__name__ == 'dict'):
            model_dict = model_store.get(model_identifier, None)

        if model_dict:
            model = model_class(**model_dict)
    else:
        model = (
            model_class.query
                       .filter_by(**filter_by_kwargs)
                       .first())

    if not model:
        try:
            model = model_class.default_content()[model_identifier]
        except KeyError:
            abort(404)


    form = DateEditForm()