Esempio n. 1
0
def create_project():
    config.reload()
    form = ProjectForm()
    ds_forms = dict([
        (cls.populates, cls()) for cls in DataSourceForm.__subclasses__()])

    form.datasource_type.choices = [
        (cls.populates, cls.name) for cls in DataSourceForm.__subclasses__()]
    form.datasource_type.choices.insert(0, (None, "-- Select Data Source --"))
    new_project = Project()

    if form.validate_on_submit():
        form.populate_obj(new_project)
        ds_form = ds_forms[form.datasource_type.data]

        if ds_form.validate():
            new_project.datasource = \
                getattr(models, form.datasource_type.data)()
            ds_form.populate_obj(new_project.datasource)

            db.session.add(new_project)
            db.session.commit()
            flash("New project successfully created.")
            return redirect(url_for('view_project', id=new_project.id))

    return render_template("project/create.html",
                           form=form, ds_forms=ds_forms, project=new_project)
Esempio n. 2
0
def create_project():
    form = ProjectForm()
    if request.method == 'POST' and form.validate_on_submit():
        name = form.name.data
        list_of_names = [
            project.project_name for project in Project.query.filter_by(
                company_id=current_user.company_id).all()
        ]
        if name not in list_of_names:
            description = form.description.data
            project = Project()
            project.project_name = name
            project.description = description
            project.company_id = current_user.company_id
            db.session.add(project)
            db.session.commit()
            return render_template(
                'error.html', message='Okay! Lets make some documentation!')
        else:
            return render_template(
                'error.html',
                message='Project with current name exist in your company.')
    return render_template('project.html',
                           user=current_user.user_username,
                           form=form)
Esempio n. 3
0
def setting_project():
    # 表格信息区
    projects = db.engine.execute(SQL['PROJECT_INFO'])
    project_choices = [(p.id, p.project_name) for p in Project.query.order_by('id')]
    user_choices = [(p.id, p.user_name) for p in User.query.filter(User.enable == 1).order_by('id')]
    # 增加项目区
    add_form = ProjectForm()
    add_form.project_manager.choices = user_choices
    if add_form.validate_on_submit():
        if g.user.role == 0:
            try:
                new_project = Project(add_form.project_name.data, add_form.project_manager.data,
                                      add_form.build_year.data, add_form.status.data)
                db.session.add(new_project)
                db.session.commit()
                log('project', '增加项目', new_project.id, new_project.project_name, '成功')
                flash("项目添加成功!")
            except Exception, e:
                flash("无法添加项目!")
                print Exception, e
                return render_template('setting-project.html', data=projects, user_choices=user_choices,
                                       status_choices=PROJECT_STATUS, add_form=add_form,
                                       project_choices=project_choices, atr='show')
        else:
            flash("无权限操作!")
Esempio n. 4
0
def edit_project(id):
    project = Project.query.get_or_404(id)

    ds_forms = dict([
        (cls.populates, cls()) for cls in DataSourceForm.__subclasses__()])
    for populates, ds_form in ds_forms.items():
        if populates == project.datasource.__class__.__name__:
            ds_forms[populates] = ds_form.__class__(obj=project.datasource)
            current_ds_type = populates

    form = ProjectForm(obj=project, datasource_type=current_ds_type)
    form.datasource_type.choices = [
        (cls.populates, cls.name) for cls in DataSourceForm.__subclasses__()]
    form.datasource_type.choices.insert(0, (None, "-- Select Data Source --"))

    if form.validate_on_submit():
        form.populate_obj(project)
        ds_form = ds_forms[form.datasource_type.data]

        if ds_form.validate():
            project.datasource = getattr(models, form.datasource_type.data)()
            ds_form.populate_obj(project.datasource)

            db.session.add(project)
            db.session.commit()
            flash("Project %s successfully updated." % project.name)
            return redirect(url_for('view_project', id=project.id))

    return render_template("project/edit.html",
                           form=form, ds_forms=ds_forms, project=project)
Esempio n. 5
0
def edit_project(project_id):
    """
    Route to edit a project in the database and redirect to index page
    """
    projects = mongo.db.Projects
    the_project = mongo.db.Projects.find_one({'_id': ObjectId(project_id)})
    form = ProjectForm()
    form.project_name.data = the_project['project_name']
    form.short_text.data = the_project['short_text']
    form.long_text.data = the_project['long_text']
    form.image1.data = the_project['image0']
    form.image2.data = the_project['image1']
    form.image3.data = the_project['image2']
    form.image4.data = the_project['image3']
    form.website_link.data = the_project['website_link']
    form.git_link.data = the_project["git_link"]

    if request.method == 'POST' and form.validate_on_submit():
        projects.update({'_id': ObjectId(project_id)},
                        {
            'project_name': request.form.get('project_name'),
            'short_text': request.form.get('short_text'),
            'long_text': request.form.get('long_text'),
            'image0': request.form.get('image1'),
            'image1': request.form.get('image2'),
            'image2': request.form.get('image3'),
            'image3': request.form.get('image4'),
            'website_link': request.form.get('website_link'),
            'git_link': request.form.get('git_link')
        })
        return redirect(url_for('index'))
    return render_template('pages/edit/project.html',
                           project=the_project, form=form)
Esempio n. 6
0
def create_project():
    config.reload()
    form = ProjectForm()
    ds_forms = dict([(cls.populates, cls())
                     for cls in DataSourceForm.__subclasses__()])

    form.datasource_type.choices = [(cls.populates, cls.name)
                                    for cls in DataSourceForm.__subclasses__()]
    form.datasource_type.choices.insert(0, (None, "-- Select Data Source --"))
    new_project = Project()

    if form.validate_on_submit():
        form.populate_obj(new_project)
        ds_form = ds_forms[form.datasource_type.data]

        if ds_form.validate():
            new_project.datasource = \
                getattr(models, form.datasource_type.data)()
            ds_form.populate_obj(new_project.datasource)

            db.session.add(new_project)
            db.session.commit()
            flash("New project successfully created.")
            return redirect(url_for('view_project', id=new_project.id))

    return render_template("project/create.html",
                           form=form,
                           ds_forms=ds_forms,
                           project=new_project)
Esempio n. 7
0
def edit_project(id):
    project = Project.query.get_or_404(id)

    ds_forms = dict([(cls.populates, cls())
                     for cls in DataSourceForm.__subclasses__()])
    for populates, ds_form in ds_forms.items():
        if populates == project.datasource.__class__.__name__:
            ds_forms[populates] = ds_form.__class__(obj=project.datasource)
            current_ds_type = populates

    form = ProjectForm(obj=project, datasource_type=current_ds_type)
    form.datasource_type.choices = [(cls.populates, cls.name)
                                    for cls in DataSourceForm.__subclasses__()]
    form.datasource_type.choices.insert(0, (None, "-- Select Data Source --"))

    if form.validate_on_submit():
        form.populate_obj(project)
        ds_form = ds_forms[form.datasource_type.data]

        if ds_form.validate():
            project.datasource = getattr(models, form.datasource_type.data)()
            ds_form.populate_obj(project.datasource)

            db.session.add(project)
            db.session.commit()
            flash("Project %s successfully updated." % project.name)
            return redirect(url_for('view_project', id=project.id))

    return render_template("project/edit.html",
                           form=form,
                           ds_forms=ds_forms,
                           project=project)
Esempio n. 8
0
def selectproject():
    arc = gis.GIS(username=session.get('arcuser'),
                  password=session.get('arcsenha'))
    mytoken = session.get('mytoken')

    listaprojetos = session.get('listaprojetos')

    form = ProjectForm()
    form.selecionaprojeto.choices = listaprojetos

    if form.validate_on_submit():
        items = arc.content.search(
            query="NOT title: %stakeholder% AND NOT title: %fieldworker% AND "
            + "owner:" + arc.users.me.username + " AND Survey",
            item_type="Feature Layer",
            max_items=500)
        session['projectname'] = str(form.selecionaprojeto.data)

        flash(
            f'Projeto ' + session.get('projectname') +
            ' selecionado com sucesso!', 'success')
        return redirect(url_for('selectcategory', mytoken=session['mytoken']))
    else:
        flash(
            'Projeto não pode ser selecionado. Verifique se há registros na camada.',
            'danger')

    return render_template('selectprojecto.html',
                           title='SelectProject',
                           mytoken=mytoken,
                           form=form)
Esempio n. 9
0
def edit_project(id):
    """
    Edit a project
    """
    check_admin()

    add_project = False

    project = Project.query.get_or_404(id)
    form = ProjectForm(obj=project)
    if form.validate_on_submit():
        project.name = form.name.data
        project.description = form.description.data
        db.session.commit()
        flash('You have successfully edited the project.')

        # redirect to the projects page
        return redirect(url_for('admin.list_projects'))

    form.description.data = project.description
    form.name.data = project.name
    return render_template('admin/projects/project.html',
                           action="Edit",
                           add_project=add_project,
                           form=form,
                           project=project,
                           title="Edit Project")
Esempio n. 10
0
def project_new():
    project = Project()
    form = ProjectForm(request.form, project)
    if form.validate_on_submit():
        counter = Counter.objects(id_for="project")[0]
        counter.set_next_id()
        counter.save()
        form.populate_obj(project)
        project.number = counter.number
        project.save()
        return redirect('/projects/')
    return render_template('projects_create.html', project=project, form=form)
Esempio n. 11
0
def welcome():
    project_form = ProjectForm()
    context = {"project_form": project_form}
    if project_form.validate_on_submit():
        title = project_form.title.data
        description = project_form.description.data
        pro = Project(title=title, description=description)
        if (pro is not None):
            db.session.add(pro)
            db.session.commit()
            return (redirect("/welcome"))
    return (render_template("welcome.html", **context))
Esempio n. 12
0
def selectproject():
    mytoken = session.get('mytoken')
    payload = {}
    headers = {
        'Account': 'stesa',
        'Token': mytoken,
    }
    prjurl = 'https://api.inventsys.com.br/v4/projects'
    projetos = requests.request('GET',
                                prjurl,
                                headers=headers,
                                data=payload,
                                allow_redirects=False)
    listaprojetos = projetos.json()['projects']

    variavelprj = ""
    variavelnome = ""
    listaprj = []
    listanomes = []
    for i in range(0, len(projetos.json()['projects'])):
        prj = (projetos.json()['projects'][i]['id'])
        nome = (projetos.json()['projects'][i]['name'])
        variavelprj = (str(prj))
        listaprj.append(variavelprj)
        variavelnome = (str(nome))
        listanomes.append(variavelnome)
    tulpa = [(x, y) for x, y in zip(listaprj, listanomes)]

    form = ProjectForm()
    form.selecionaprojeto.choices = tulpa

    if form.validate_on_submit():
        if projetos:
            session['project'] = str(form.selecionaprojeto.data)
            session['projectname'] = str(
                dict(form.selecionaprojeto.choices).get(
                    form.selecionaprojeto.data))
            flash(
                f'Projeto ' + session['projectname'] +
                ' selecionado com sucesso!', 'success')
            return redirect(
                url_for('selectcategory',
                        mytoken=session['mytoken'],
                        project=session['project']))
        else:
            flash('Projeto não pode ser selecionado. Tente novamente.',
                  'danger')

    return render_template('selectprojecto.html',
                           title='SelectProject',
                           mytoken=mytoken,
                           form=form)
Esempio n. 13
0
def add_project():
    form = ProjectForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            new_project = Projects(form.name.data, form.category.data, form.info.data, form.slug.data,
                                   form.status.data, github=form.github.data, url=form.url.data)
            db.session.add(new_project)
            db.session.commit()
            flash('New project added')
        else:
            flash('Validation failed')

    return render_template('new.html', form=form)
Esempio n. 14
0
def edit(name):
    form = ProjectForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            selected_project = Projects.query.filter(Projects.slug == name).first()
            selected_project.update(form)
            db.session.commit()
            flash('Project edited')
        else:
            flash('Validation error')
    return render_template('edit.html',
                           project=Projects.query.filter(Projects.slug == name).first(),
                           form=form)
Esempio n. 15
0
def create_project():
    project_form = ProjectForm()
    project_form.course_id.choices = course_choices()

    if project_form.validate_on_submit():
        rowcount = db.create_project({
            'name': project_form.name.data,
            'course_id': project_form.course_id.data
        })
        if rowcount == 1:
            flash('Project {} created'.format(project_form.name.data))
            return redirect(url_for('all_projects'))
    return render_template('projects/add.html', form=project_form)
Esempio n. 16
0
def project_new():
    project = Project()
    form = ProjectForm(request.form, project)
    if form.validate_on_submit():
        counter = Counter.objects(id_for="project")[0]
        counter.set_next_id()
        counter.save()
        form.populate_obj(project)
        project.number = counter.number
        project.save()
        return redirect('/projects/')
    return render_template('projects_create.html',
                           project=project,
                           form=form)
Esempio n. 17
0
File: app.py Progetto: Red54/Sophia
def project_setting(project_id):
    project = Project.query.get(project_id)
    if current_user.id != project.creator_id:
        abort(404)
    form = ProjectForm(user=current_user, team=project.team, project=project, team_id=project.team.id,
                       name=project.name, subject=project.subject)
    form.team_id.choices = [(g.id, g.name) for g in current_user.teams]
    if form.validate_on_submit():
        if request.form.get('delete'):
            project.status = 1
            db.session.add(project)
            db.session.commit()
            return redirect(url_for('run'))
        return redirect(url_for('project_index', project_id=form.project.id))
    return render_template('project/form.html', form=form)
Esempio n. 18
0
def edit_project(id):
    project_info = Project.query.get(id)
    image = project_info.screenshot
    edit_project = ProjectForm(
        name=project_info.name,
        link=project_info.link,
        github_link=project_info.github_link,
        screenshot=None,
        description=project_info.description,
        tech_list=project_info.tech_list,
    )
    if edit_project.validate_on_submit():
        s3_client = s3_session.resource("s3")
        file = request.files["screenshot"]
        if file:

            if file.filename == "":
                flash("Image must have file name.")
                return redirect(request.url)

            if not allowed_image(file.filename, current_app):
                flash("That image extension is not allowed.")
                return redirect(request.url)

            try:
                s3_client.Object(current_app.config["S3_BUCKET"],
                                 image).delete()
            except:
                pass

            filename = secure_filename(str(
                uuid.uuid4())) + f".{image_ext(file.filename)}"
            s3_client.Bucket(current_app.config["S3_BUCKET"]).put_object(
                Key=filename, Body=file, ACL="public-read")
            project_info.screenshot = filename

        project_info.name = edit_project.name.data
        project_info.link = edit_project.link.data
        project_info.github_link = edit_project.github_link.data
        project_info.description = edit_project.description.data
        project_info.tech_list = edit_project.tech_list.data
        db.session.commit()
        return redirect(url_for("main_page.home") + "#Project")

    return render_template("form_page.html",
                           form=edit_project,
                           title="Project",
                           image=image)
Esempio n. 19
0
def project_create():
    form = ProjectForm()
    if form.validate_on_submit():
        new_project = Project(
            title=form.title.data,
            branch=form.branch.data,
            user_id=current_user.get_id(),
            repo_url=form.repo_url.data
        )
        db.session.add(new_project)
        db.session.commit()

        flash('Project has been created successfully.', 'success')
        return redirect(url_for('project', project_id=new_project.id))

    return render_template('project/form.html', form=form, action_url=url_for('project_create'))
Esempio n. 20
0
def add_project():
    form = ProjectForm()
    round = 1
    if form.validate_on_submit():
        project_name=form.data["name"]
        project_subtitle=form.data["subtitle"]
        project_text=form.data["body"]
        project_img=form.data["img_url"]
        new_project =  Project(title=project_name,
                               subtitle=project_subtitle,
                               body=project_text,
                               img_url=project_img)
        db.session.add(new_project)
        db.session.commit()
        return redirect(url_for("myprojects"))
    return render_template("addproject.html", form=form, round=round,user=current_user)
Esempio n. 21
0
def editproject(id):
    project = Project.query.get(id)
    edit_form = ProjectForm(
        name=project.title,
        subtitle=project.subtitle,
        img_url=project.img_url,
        body=project.body
    )
    if edit_form.validate_on_submit():
        project.title = edit_form.name.data
        project.subtitle = edit_form.subtitle.data
        project.img_url = edit_form.img_url.data
        project.body = edit_form.body.data
        db.session.commit()
        return redirect(url_for("project", id=project.id))

    return render_template("addproject.html", form=edit_form, is_edit=True, user=current_user)
Esempio n. 22
0
def index():
    form = ProjectForm()
    if form.validate_on_submit():
        project_name = request.form['name']
        api_type = request.form['api_type']

        project = Project(
                          name=project_name,
                          api_type=api_type,
                          created_by=current_user.id
                        )
        db.session.add(project)
        db.session.commit()
        flash('Project Created')
        return redirect(url_for('main_site_index.index'))

    return render_template('main/api_auth.html', form=form)
Esempio n. 23
0
def project(id_project=None):
    from forms import ProjectForm
    if id_project != None:
        project = Project.query.get(id_project)
        action = "Save"
    else:
        project = Project()
        action = "Create"
        
    form = ProjectForm(obj=project)
    if form.validate_on_submit():
        form.populate_obj(project)
        project.users.append(current_user)
        db.session.add(project)
        db.session.commit()
        return redirect('/projects')
    
    return render_template('project/form.html', form=form, action=action)
Esempio n. 24
0
def add_project():
    project_query = Project.query.filter_by(general_id=current_user.id)
    form = ProjectForm()
    if request.method == "POST" and form.validate_on_submit():
        project_query_count = 1
        if project_query:
            project_query_count = project_query.count() + 1
        s3_client = s3_session.resource("s3")
        file = request.files["screenshot"]

        if file:

            if file.filename == "":
                flash("Image must have file name.")
                return redirect(request.url)

            if not allowed_image(file.filename, current_app):
                flash("That image extension is not allowed.")
                return redirect(request.url)

            filename = secure_filename(str(
                uuid.uuid4())) + f".{image_ext(file.filename)}"
            s3_client.Bucket(current_app.config["S3_BUCKET"]).put_object(
                Key=filename, Body=file, ACL="public-read")

        else:
            filename = None

        new_project = Project(
            name=form.name.data,
            link=form.link.data,
            github_link=form.github_link.data,
            screenshot=filename,
            description=form.description.data,
            tech_list=form.tech_list.data,
            general=current_user,
            order_project=project_query_count,
        )
        db.session.add(new_project)
        db.session.commit()
        return redirect(url_for("main_page.home") + "#Project")

    return render_template("form_page.html", form=form, title="Project")
Esempio n. 25
0
def newproject():
    error = None
    form = ProjectForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            print 'validated'
            new_project = Project(
                form.subject.data,
                form.discription.data,
                form.duedate.data,
                form.finished.data,
                form.download_file.data,
            )
            db.session.add(new_project)
            db.session.commit()
            flash(u'پروژه ثبت شد ممد!')
        else:
            print 'not!'
    return render_template('newproject.html', form=form, error=error)
Esempio n. 26
0
def newproject():
    error = None
    form = ProjectForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            print 'validated'
            new_project = Project(
                form.subject.data,
                form.discription.data,
                form.duedate.data,
                form.finished.data,
                form.download_file.data,
            )
            db.session.add(new_project)
            db.session.commit()
            flash(u'پروژه ثبت شد ممد!')
        else:
            print 'not!'
    return render_template('newproject.html', form=form, error=error)
Esempio n. 27
0
def add_project():
    """
    Route to add a project to the database and redirect to index page
    """
    projects = mongo.db.Projects
    form = ProjectForm()

    if request.method == 'POST' and form.validate_on_submit():
        projects.insert(
            {
                'project_name': request.form.get('project_name'),
                'short_text': request.form.get('short_text'),
                'long_text': request.form.get('long_text'),
                'image0': request.form.get('image1'),
                'image1': request.form.get('image2'),
                'image2': request.form.get('image3'),
                'image3': request.form.get('image4'),
                'website_link': request.form.get('website_link'),
                'git_link': request.form.get('git_link')
            })
        return redirect(url_for('index'))
    return render_template('pages/add/project.html', form=form)
Esempio n. 28
0
def create_project():
    form = ProjectForm()
    if form.validate_on_submit():
        team_name = form.team_name.data
        project_name = form.project_name.data
        selected_tags = form.tags.data
        about = form.about.data
        user = User.query.filter_by(nickname=current_user.nickname).first()

        project = Project(team_name=team_name,
                          project_name=project_name,
                          about=about,
                          admin=user,
                          logo=url_for(
                              'static',
                              filename=f'project_logos/{team_name}.jpg'))

        filename = form.team_name.data + '.jpg'
        logo_file = open(os.getcwd() + '/static/project_logos/' + filename,
                         'wb')
        default_logo = open(
            os.getcwd() + '/static/site-images/' + 'default-project-logo.jpg',
            'rb')
        logo_file.write(default_logo.read())
        project.members.append(user)
        logo_file.close()
        default_logo.close()
        for tag in selected_tags:
            t = Tag.query.filter_by(name=tag).first()
            project.tags.append(t)
        db.session.add(project)
        db.session.commit()
        return redirect(url_for('get_project',
                                p=project.team_name))  #!!!!!Change

    tags = Tag.query.all()
    return render_template('for_project_model/create.html',
                           form=form,
                           tags=tags)
Esempio n. 29
0
def add_project():
    """
    Add a project to the database
    """
    check_admin()

    add_project = True

    form = ProjectForm()
    if form.validate_on_submit():
        project = Project(name=form.name.data,
                          description=form.description.data)
        try:
            # add project to the database
            db.session.add(project)
            db.session.commit()
            flash('You have successfully added a new project.')
        except:
            # in case project name already exists
            flash('Error: project name already exists.')

    # redirect to projects page
    return redirect(url_for('admin.list_projects'))
Esempio n. 30
0
def create_project(record_id=False):
    form = ProjectForm()
    if form.validate_on_submit():
        values = {
            'name': form.name.data,
            'description': form.description.data,
            'color': form.color.data,
            'date': form.date.data,
        }
        if current_user.data.get('id') and not record_id:
            values['user_id'] = current_user.data.get('id')
        if record_id:
            table_registry.projects.write([record_id], values)
        else:
            table_registry.projects.create(values)
        return json.dumps({'redirect': url_for('home')})
    elif record_id:
        project_data = table_registry.projects.search_read([['id', '=', record_id]])[0]
        form.name.data = project_data['name']
        form.description.data = project_data['description']
        form.color.data = project_data['color']
        form.date.data = project_data['date'].strftime('%m/%d/%Y %I:%M %p')
    return render_template('backend/project_model.html', form=form, record_id=record_id and str(record_id))
Esempio n. 31
0
File: app.py Progetto: Red54/Sophia
def project_create():
    form = ProjectForm(user=current_user, team_id=request.args.get('team_id'))
    form.team_id.choices = [(g.id, g.name) for g in current_user.teams]
    if form.validate_on_submit():
        return redirect(url_for('project_index', project_id=form.project.id))
    return render_template('project/form.html', form=form)
Esempio n. 32
0
def project_edit(project_id):
    """ Renders form to edit specific project or process the form """

    if not 'CURR_USER_KEY' in session:
        flash("Unauthorized access. Account needed to edit.", "danger")
        return redirect(f"/project/{project_id}")

    project = Project.lookup_project(project_id)
    project = Project.lookup_project(project_id)
    if g.user.id != project.user.id:
        flash("Unauthorized user. Correct user account needed.", "danger")
        return redirect(f"/project/{project_id}")

    form = ProjectForm(obj=project, prefix='form-project-edit-')

    tags_full_list = Tag.list_all()
    project_tags = [tag.name for tag in project.tags]
    tags_list_str = "|".join(project_tags)

    if form.validate_on_submit():
        project.name = form.name.data
        project.description = form.description.data
        project.user_id = g.user.id
        project.contact_info_type = form.contact_info_type.data
        project.contact_info = form.contact_info.data
        project.lat = form.lat.data
        project.long = form.long.data
        project.pic_url1 = request.form.get('pic_url1')
        project.pic_url2 = request.form.get('pic_url2')

        tags = request.form.get('tags')
        if (tags):
            tags = tags.split('|')
        tag_objs = []
        if (tags and len(tags) > 0):
            for name in tags:
                tag_obj = Tag.lookup_tag(name)
                if not tag_obj:
                    tag_obj = Tag.create_tag(name)
                tag_objs.append(tag_obj)
        project.tags = tag_objs

        optional_date_keys = ['inquiry_deadline', 'work_start', 'work_end']
        optional_date_values = []
        for each in optional_date_keys:
            try:
                y, m, d = request.form.get(each).split('-')
                print(y, m, d, 'out of if')
                if y and m and d:
                    date = datetime(int(y), int(m), int(d))
                    optional_date_values.append(date)
                    print(date, 'in if', optional_date_values)
            except ValueError:
                pass
                optional_date_values.append(None)
                print('caught value error', optional_date_values)
            except AttributeError:
                optional_date_values.append(None)
                print('caught value error', optional_date_values)
        project.inquiry_deadline, project.work_start, project.work_end = optional_date_values
        db.session.commit()

        flash("Project edited successfully.", "success")
        return redirect(f"/project/{project_id}")

    return render_template("project-edit.html",
                           form=form,
                           project=project,
                           tags_list_str=tags_list_str,
                           tags_full_list=tags_full_list)
Esempio n. 33
0
def project_new():
    """ Renders form to create new project or process the form """

    if not 'CURR_USER_KEY' in session:
        flash("Unauthorized access. Account needed to create.", "danger")
        if 'GUEST_GEOCODE' in session:
            return redirect("/search")
        else:
            return redirect("/")

    form = ProjectForm(prefix='form-project-new-')
    tags_full_list = Tag.list_all()

    if form.validate_on_submit():
        optional_date_keys = ['inquiry_deadline', 'work_start', 'work_end']
        optional_date_values = []
        for each in optional_date_keys:
            try:
                y, m, d = request.form.get(each).split('-')
                print(y, m, d, 'out of if')
                if y and m and d:
                    date = datetime(int(y), int(m), int(d))
                    optional_date_values.append(date)
                    print(date, 'in if', optional_date_values)
            except ValueError:
                optional_date_values.append(None)
                print('caught value error', optional_date_values)
            except AttributeError:
                optional_date_values.append(None)
                print('caught value error', optional_date_values)
        inquiry_deadline_date, work_start_date, work_end_date = optional_date_values

        project_obj = {
            'name': form.name.data,
            'description': form.description.data,
            'user_id': g.user.id,
            'contact_info_type': form.contact_info_type.data,
            'contact_info': form.contact_info.data,
            'lat': form.lat.data,
            'long': form.long.data,
            'inquiry_deadline': inquiry_deadline_date,
            'work_start': work_start_date,
            'work_end': work_end_date,
            'pic_url1': request.form.get('pic_url1'),
            'pic_url2': request.form.get('pic_url2'),
        }
        project_final = Project.create_project(project_obj)

        tags = request.form.get('tags')
        if tags:
            tags = tags.split('|')
            tag_objs = []
            if (len(tags) > 0):
                for name in tags:
                    tag_obj = Tag.lookup_tag(name)
                    if not tag_obj:
                        tag_obj = Tag.create_tag(name)

                    tag_objs.append(tag_obj)
                project_final.tags = tag_objs
                db.session.commit()

        flash("Project created successfully", "success")
        return redirect(f"/project/{project_final.id}")

    return render_template("project-new.html",
                           form=form,
                           tags_full_list=tags_full_list)