Пример #1
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)
Пример #2
0
def edit_project(request, project_id=None):
    # http://wiki.ddenis.com/index.php?title=Django,_add_and_edit_object_together_in_the_same_form

    if project_id:
        print "exists"
        project = get_object_or_404(Project, pk=project_id)
        if request.user not in project.users.all():
            return HttpResponseForbidden()
    else:
        print "doesn't exist"
        project = Project()

    if request.method == "POST":

        form = ProjectForm(request.POST, instance=project)

        if form.is_valid():

            form.save()

            return HttpResponseRedirect(project.get_absolute_url())

    else:

        form = ProjectForm(instance=project)

    if project_id:
        template_name = "edit_project.html"
    else:
        template_name = "new_project.html"

    return render(request, template_name, {"form": form, "project": project})
Пример #3
0
def create_project(request):
    user = request.user
    if request.POST:
        form = ProjectForm(request.POST, request.FILES)
        if form.is_valid():
            c = form.save(commit=False)
            c.author = user
            c.save()
            #            import pdb; pdb.set_trace()
            project = Project.objects.get(id=c.id)
            ## permissions
            if not project.public:
                group = '{}_pr_workers'.format(c.id)
                group = Group.objects.create(name=group)
                group.save()
            else:
                group = Group.objects.get(name='workers')
#            import pdb; pdb.set_trace()
            for i in worker_perms['project']:
                assign_perm(i, group, project)
            for i in prcreator_perms:
                assign_perm(i, user, project)
            user.groups.add(group)
            loger(auth.get_user(request), 'created project',c.name, project=project)
            return HttpResponseRedirect('/projector/all')
    else:
        form = ProjectForm()
     #   import pdb; pdb.set_trace()
        #form['deadline'] = '111'

    args = {}
    args['username'] = auth.get_user(request).username
    args.update(csrf(request))
    args['form'] = form
    return render_to_response('create_project.html',args)
Пример #4
0
def project_edit(request, pid, template_name='project_new.html'):
    """
    Edit an existing project
    """
    namedup = None
    project = get_object_or_404(request.user.project_set, id=pid)
    if request.method == "POST":
        form = ProjectForm(request.POST, instance=project)
        if form.is_valid():
            try:
                form.save()
                url = reverse('bbotweb_project_show', kwargs={'pid':project.id})
                return HttpResponseRedirect(url)
            except IntegrityError:
                msg = _("You already have a %s with the same name (%s).")
                messages.error(request, msg % (_("project"), project.name)); 
                namedup = True
    else:
        form = ProjectForm(instance=project)
    
    return render_to_response(template_name, {
        'form' : form,
        'project' : project,
        'namedup' : namedup,
    }, context_instance=RequestContext(request))
Пример #5
0
def project_detail_view(request,id):
    context = {'current':'projects'}
    user = request.user
    project = Project.objects.get_for_user(user=request.user, id=int(id))

    if request.POST:
        form = ProjectForm(instance=project, data=request.POST)
        if form.is_valid():
            form.save()
            context['project_saved'] = True
        context['form'] = form
    else:
        context['form'] = ProjectForm(instance=project)

    context['project'] = project
    context['spectators'] = project.spectators.all().select_related()
    context['owners'] = project.owners.all().select_related()
    context['collaborators'] = project.collaborators.all().select_related()
    context['new_spectators'] = User.objects.filter(profile__contacts__user=request.user).exclude(projects_as_spectator = project).select_related()
    context['new_collaborators'] = User.objects.filter(profile__contacts__user=request.user).exclude(projects_as_collaborator = project).select_related()
    context['is_creator'] = project.is_creator(request.user)
    context['is_admin'] = project.is_admin(request.user)
    context['new_owners'] = User.objects.filter(profile__contacts__user=request.user).exclude(owned_projects = project).select_related()
    context['new_task_form'] = NewTaskForm()
    context['goal_form'] = GoalForm()
    return render_response(request, 'project/project_detail_view.html', context)
Пример #6
0
def form():
	form = ProjectForm()
	email = session['email']
	project_id = project_nums()
	user = User.query.filter_by(email=email).first()
	user_id = user.uid
	firstname, lastname = user.firstname, user.lastname
	
	if request.method == "POST":
		if form.validate() == False:
			return render_template('form.html', form=form, firstname=firstname, lastname=lastname)
		else:
			name = form.groupname.data
			goal = form.goal.data
			accomplish = form.accomplish.data
			friends = form.friends.data
			new_user_project = Projects(project_id, name, user_id, goal, accomplish)
			if friends:
				friends = friends.split(" ")
				for i in friends:
					friend = None
					if "@" in i:
						friend = User.query.filter_by(email=i[1:-2]).first()
						friend_id = friend.uid
					if friend:
						new_friend_project = Projects(project_id, name, friend_id, '', '')
						db.session.add(new_friend_project)
						db.session.commit()
			db.session.add(new_user_project)
			db.session.commit()

			return redirect(url_for('home', firstname = firstname, lastname = lastname))


	return render_template("form.html", form=form, firstname=firstname, lastname= lastname)
Пример #7
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)
Пример #8
0
def create_project():

  if 'email' not in session:
    return redirect(url_for('home'))

  show_project = ProjectForm()
  show_project.set_supervisor_choices()

  if request.method == 'POST':
    if show_project.validate() == False:
      flash('All fields are required.')
      return render_template('create_project.html', show_project=show_project)
    else:
      new_project = project(show_project, session['email'])
      db.session.add(new_project)
      db.session.commit()
      if show_project.file.data.filename:
        os.makedirs("Project/files/" + str(newuser.id))
        filename = secure_filename(show_project.file.data.filename)
        show_project.file.data.save('Project/files/' + str(newuser.id) + "/" + filename)
      flash('Project has been created')
      return redirect(url_for('create_project'))
 
  elif request.method == 'GET':
    return render_template('create_project.html', show_project=show_project) 
Пример #9
0
def create(request):
    if request.method == 'POST':

        form = ProjectForm(request.POST)

        if form.is_valid():

            title = form.cleaned_data['title']
            inv_type = form.cleaned_data['investigation_type']
            desc = form.cleaned_data['description']

            body = {
                "name":"idsvc.project",
                "value": {
                    "title":title,
                    "investigation_type":inv_type,
                    "description":desc,
                }
            }
            a = _client(request)
            try:
                response = a.meta.addMetadata(body=body)
            except Exception as e:
                logger.debug('no sir: %s' % e)

            return HttpResponseRedirect('/projects/')
    # else:
    context = {
        'form': ProjectForm()
    }

    return render(request, 'ids_projects/create.html', context)
Пример #10
0
def edit_project(request, projectId):
    context = RequestContext(request)
    user = request.user
    project = Project.objects.get(pk=projectId)
    project_dict = model_to_dict(project)
    user_is_owner(user, project)
    redirect = get_redirect_url(request)

    if request.method == "POST":
        p = ProjectForm(request.POST, request.FILES, questions=project.rfp.get_project_questions())

        if p.is_valid():
            p_data = p.cleaned_data
            p_update = Project.objects.update_or_create(user=user, id=project.id, defaults=p_data)
            proj = p_update[0]
            proj_save = proj.save()

            return HttpResponseRedirect(redirect)

    else:
        p = ProjectForm(initial=project_dict, questions=project.rfp.get_project_questions())

    context_dict = {"project": project, "user": user, "form": p}

    return render_to_response("rfp/edit_project.html", context_dict, context)
Пример #11
0
def project_add_typed(request, project_id, response_format='html'):
    """Project add to preselected parent project"""

    parent_project = None
    if project_id:
        parent_project = get_object_or_404(Project, pk=project_id)
        if not request.user.profile.has_permission(parent_project, mode='x'):
            parent_project = None

    if request.POST:
        if 'cancel' not in request.POST:
            project = Project()
            form = ProjectForm(
                request.user.profile, project_id, request.POST, instance=project)
            if form.is_valid():
                project = form.save()
                project.set_user_from_request(request)
                return HttpResponseRedirect(reverse('projects_project_view', args=[project.id]))
        else:
            return HttpResponseRedirect(reverse('projects'))
    else:
        form = ProjectForm(request.user.profile, project_id)

    context = _get_default_context(request)
    context.update({'form': form, 'project': parent_project})

    return render_to_response('projects/project_add_typed', context,
                              context_instance=RequestContext(request), response_format=response_format)
Пример #12
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("无权限操作!")
Пример #13
0
 def add(self):
     form = ProjectForm(csrf_enabled=False)
     if form.validate():
         project = form.save()
         db.session.add(project)
         db.session.commit()
         return 201, project.id
     return 400, form.errors
Пример #14
0
def add_project():
    form = ProjectForm(request.form)
    if not form.validate():
        return str(form.errors)
    project = Project(form.name.data)
    db.session.add(project)
    db.session.commit()
    return redirect(url_for('index'))
Пример #15
0
def pep_view(request, **view_args):
    if request.method == 'GET':
        form = ProjectForm(request.GET)

        if form.is_valid():
            run_pep8(form.cleaned_data['url'], form.path, form.name, form.rev)
            return HttpResponseRedirect('/%s/%s' % (form.name, form.rev))

    return __show_home(form)
Пример #16
0
def new_project(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/projects/')
    else:
        form = ProjectForm()
    return render_to_response('new_project.html',{'form': form})
Пример #17
0
def create_project(request, template="create_project.html"):
    user = get_object_or_404(User, pk=request.user.pk)
    form = ProjectForm(request.POST or None, initial={"user": user})
    if request.method == "POST" and form.is_valid():
        new_project = form.save()
        print new_project
        return redirect("enterprise.projects")
    context = {"form": form, "title": _("Create Project"), "enterprise": request.session["company"]}
    return render(request, template, context)
Пример #18
0
def add(request):
    if request.method == "POST":
        form = ProjectForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect("core:home")
    else:
        form = ProjectForm()
    return render_to_response("add.html", {"form": form}, context_instance=RequestContext(request))
Пример #19
0
def add_project(request):
	if request.method == 'GET':
		form = ProjectForm()
	elif request.method == 'POST':
		form = ProjectForm(request.POST)
		if form.is_valid():
			form.save()
	return render_to_response ('devcup/add_project.html', {
		'form': form,
	}, context_instance = RequestContext(request))
Пример #20
0
def create_project(request):
    """ Create a new Project.

    """
    form = ProjectForm(request.POST or None)
    if form.is_valid():
        new_project = form.save()
        return redirect(details_project, project_id=new_project.key)
    return render_to_response('form.html', {'form': form},
                              context_instance=RequestContext(request))
Пример #21
0
def edit_project2(project_id):

  if 'email' not in session:
    return redirect(url_for('home'))

  project_By_ID = project.query.filter_by(id = project_id).first_or_404()

  show_project = ProjectForm()
  show_project.set_supervisor_choices()

  show_project.setFormContentFromProject(project_By_ID)

  if request.method == 'POST':
    show_project = ProjectForm()
    show_project.set_supervisor_choices()
    if show_project.validate() == False:
      flash('Please fill out everything')
      return render_template('edit_project.html', show_project=show_project, projectByID = project_By_ID)
    else:
      project_By_ID.updateProject(show_project)
      db.session.add(project_By_ID)
      db.session.commit()
      return redirect(url_for('home'))
                     
  elif request.method == 'GET':
    return render_template('edit_project.html', show_project=show_project, projectByID = project_By_ID)
Пример #22
0
def create_project(request):
    """ Create a new Project.

    """
    form = ProjectForm(request.POST or None)
    if form.is_valid():
        new_project = form.save()
        return redirect(details_project, project_id=new_project.key)
    return render_to_response('form.html',
                              {'form': form},
                              context_instance=RequestContext(request))
Пример #23
0
def  Projects_form(webdata,request):
    forms = ProjectForm(webdata)
    if forms.is_valid():
        try:
            if create_dir(webdata['project_url']):
                forms.save()
                return HttpResponseRedirect(reverse('confd:project_list'))
            else:
                return render(request, 'confd/apply_project.html', {'forms': forms, 'errmsg': '项目创建失败'})
        except:
            return render(request, 'confd/apply_project.html', {'forms': forms, 'errmsg': '项目创建失败'})
Пример #24
0
def add_project(request):
    if request.method == "POST":
        form = ProjectForm(request.POST, user=request.user)
        if form.is_valid():
            form.save(request)
            messages.success(request, "Project created successfully.")
            return HttpResponseRedirect(reverse("my_projects"))
    else:
        form = ProjectForm()
    return render_to_response(
        "authenticated/project/add_project.html", locals(), context_instance=RequestContext(request)
    )
Пример #25
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)
Пример #26
0
def create_project(request):

    if request.method == 'POST':
        form=ProjectForm(request.POST)
        if form.is_valid():
            form.save()    
            return HttpResponseRedirect("/account/")
    else:
  
            form=ProjectForm()

    return  render(request, 'PyBugs/create_project.html', {'form': form,}) 
Пример #27
0
def manage_projects(request):
    if 'pick' in request.GET:
        return _pick_project(request, request.GET['pick'])
    
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            project = form.save()
            return _pick_project(request, project)
    else:
        form = ProjectForm()
    return {'projects': Project.objects.all(), 'form': form}
Пример #28
0
def new_project(request):
    if request.method == 'POST':
        pform = ProjectForm(request.POST, instance=Project())
        if pform.is_valid():
            pform.save()
        return HttpResponseRedirect('/viewer/project/')
    else:
        pform = ProjectForm(instance=Project())
        context = {'project_form': pform}
        context.update(csrf(request))
        return render_to_response('viewer/project/new_project.html', context,
                                  context_instance=RequestContext(request))
Пример #29
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))
Пример #30
0
def create_project():
    form = ProjectForm()
    if request.method == "GET" and 'project_id' in request.values:
        form.name.data = request.values['project_id']

    if request.method == "POST":
        # At first, we don't want the user to bother with the identifier
        # so it will automatically be missing because not displayed into
        # the form
        # Thus we fill it with the same value as the filled name,
        # the validation will take care of the slug
        if not form.id.data:
            form.id.data = form.name.data
        if form.validate():
            # save the object in the db
            project = form.save()
            db.session.add(project)
            db.session.commit()

            # create the session object (authenticate)
            session[project.id] = project.password
            session.update()

            # send reminder email
            g.project = project

            message_title = _(
                "You have just created '%(project)s' "
                "to share your expenses",
                project=g.project.name)

            message_body = render_template("reminder_mail.%s" %
                                           get_locale().language)

            msg = Message(message_title,
                          body=message_body,
                          recipients=[project.contact_email])
            try:
                mail.send(msg)
            except SMTPRecipientsRefused:
                msg_compl = 'Problem sending mail. '
                # TODO: destroy the project and cancel instead?
            else:
                msg_compl = ''

            # redirect the user to the next step (invite)
            flash(
                _("%(msg_compl)sThe project identifier is %(project)s",
                  msg_compl=msg_compl,
                  project=project.id))
            return redirect(url_for(".invite", project_id=project.id))

    return render_template("create_project.html", form=form)
Пример #31
0
def project_edit(project_id):
    project = Project.query.filter_by(id=project_id).first_or_404()
    form = ProjectForm(obj=project)

    if request.method == 'POST' and form.validate():
        form.populate_obj(project)
        db.session.commit()

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

    return render_template('project/form.html', form=form, action_url=url_for('project_edit', project_id=project.id))
Пример #32
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)
Пример #33
0
def createProject(request):
    #un = User.__unicode__(request.user)
    #user = get_object_or_404(User, username = un)
    if request.method == 'POST': # If the form has been submitted...
        user = Project(owner = request.user)
        form = ProjectForm(request.POST, instance = user) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            new_project = form.save()           
            return HttpResponseRedirect('/flow/') # Redirect after POST
    else:
        form = ProjectForm() # An unbound form
        variables = RequestContext(request, { 'form': form })
        return render_to_response('flow/createproject.html', variables)
Пример #34
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)
Пример #35
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)
Пример #36
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)
Пример #37
0
def add_project(request):
    
    if request.method == 'POST':
        projectForm = ProjectForm(request.POST)
        if projectForm.is_valid():
            project = projectForm.save()
            request.user.message_set.create(message=_('Project created'))
            return redirect(project.get_absolute_url())
    else:
        projectForm = ProjectForm()
    
    return direct_to_template(request, 'picket/admin/project_add.html',
        {'project_form': projectForm,})
Пример #38
0
def getProject(*args, **kwargs):
    """
    获取业务列表
    """
    form = ProjectForm(data=kwargs)
    if not form.validate():
        return dictify(test={"code": 1}, success=False, msg=u"表单参数有误")

    project_id = form.project_id.data

    projects = Project.objects.filter(id__in=project_id).values("id", "name")
    data = list(projects)

    return dictify(test={"code": 4}, success=True, data=data)
Пример #39
0
def new_project(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        name = str(request.POST['title'])
        #list=(str(project_api.get_projects_for_user(request.user.id))).replace("<Project: ","").replace(', ','').replace('[','').replace("]",'').split('>')
        #list = project_api.get_projects_for_user(request.user.id).values_list('title',flat=True)
        #print list

        #if name in list:
        if project_api.duplicate_project(request.user, request.POST):
            form.if_dup(1)
        if form.is_valid():
            project_api.create_project(request.user, request.POST)
            project = form.save(commit=False)
            # return redirect('/req/projects')
            # return empty string and do the redirect stuff in front-end
            return HttpResponse('')

    else:
        form = ProjectForm()

    context = {
        'projects': project_api.get_projects_for_user(request.user.id),
        'canOwnProject': request.user.has_perm(PERMISSION_OWN_PROJECT),
        'title': 'New Project',
        'form': form,
        'action': '/req/newproject',
        'button_desc': 'Create Project'
    }
    return render(request, 'ProjectSummary.html', context)
Пример #40
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)
Пример #41
0
def create_project_summary(request,projectId):
    context = RequestContext(request)
    user = request.user

    project = Project.objects.get(pk = projectId)
    project_data = ProjectForm(data=model_to_dict(project),questions = project.rfp.get_project_questions())
    user_is_owner(user,project)

    budget_line_list = BudgetLine.objects.filter(project = project)
    hr_budget_line_list = BudgetLine.objects.filter(project = project,category = 'HR')
    oc_budget_line_list = BudgetLine.objects.filter(project = project,category = 'OC')
    eq_budget_line_list = BudgetLine.objects.filter(project = project,category = 'EQ')

    prop_rev_list = ProposedReviewer.objects.filter(project = project).exclude(type='USER_EXCLUDED').exclude(type='ADMIN_PROPOSED').exclude(type = 'BOARD_SUGGESTED')
    excluded_rev_list = ProposedReviewer.objects.filter(project = project, type='USER_EXCLUDED')
    total_budgeted = budget_line_sum(budget_line_list)

    if request.method == 'POST':
        project.status='submitted'
        project.save()
        project.send_project_confirmation_email()


    context_dict = {'project':project,'project_data' : project_data,'budget_line_list': budget_line_list,
                    'total' : total_budgeted,'hr_budget_lines_list' : hr_budget_line_list, 'oc_budget_lines_list' : oc_budget_line_list,
                    'eq_budget_lines_list' : eq_budget_line_list,'prop_rev_list' : prop_rev_list,'excluded_rev_list' : excluded_rev_list}

    return render_to_response('rfp/create_project_summary.html',context_dict,context)
Пример #42
0
def delete_project(request, projectID):
    project = project_api.get_project(projectID)
    if project is None:
        # return redirect('/req/projects')
        # return empty string and do the redirect stuff in front-end
        return HttpResponse('')
    if request.method == 'POST':
        project_api.delete_project(project)
        # return redirect('/req/projects')
        # return empty string and do the redirect stuff in front-end
        return HttpResponse('')
    else:
        form = ProjectForm(instance=project)

    context = {
        'projects': project_api.get_projects_for_user(request.user.id),
        'canOwnProject': request.user.has_perm(PERMISSION_OWN_PROJECT),
        'title': 'Delete Project',
        'confirm_message':
        'This is an unrevert procedure ! You will lose all information about this project !',
        'form': form,
        'action': '/req/deleteproject/' + projectID,
        'button_desc': 'Delete Project'
    }
    return render(request, 'ProjectSummary.html', context)
Пример #43
0
def home():
    project_form = ProjectForm()
    auth_form = AuthenticationForm()
    return render_template("home.html",
                           project_form=project_form,
                           auth_form=auth_form,
                           session=session)
Пример #44
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)
Пример #45
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)
Пример #46
0
def add_project(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)

        if form.is_valid():
            package = form.cleaned_data['package']
            username = form.cleaned_data['username']
            repository = form.cleaned_data['repository']
            branch = form.cleaned_data['branch']
            cargo_support = form.cleaned_data['cargo_support']
            categories = form.cleaned_data['categories']

            repo = travisclient.get_repo(username, repository)

            if not repo:
                error_message = 'Unable to get Travis CI repo: {}/{}'.\
                    format(username, repository)
                return index(request, error_message)

            project = Project(package=package,
                              username=username,
                              repository=repository,
                              branch=branch,
                              cargo_support=cargo_support)

            if ('description' in repo and repo['description']):
                project.description = repo['description']
            else:
                project.description = ''
            project.save()

            # Set categories
            project.categories = categories
            project.save()

            return authenticate_with_github(request, project.id, 'add_project')

    else:
        form = ProjectForm(initial={'branch': 'master'})

    context = {
        'title': private_settings.APP_TITLE,
        'form': form,
        'categories': ProjectCategory.objects.all()
    }
    return render(request, 'ppatrigger/project_form.html', context)
Пример #47
0
def project_view(request, project_id):
    """
    - return project corresponding to project_id
    - handle project modification form submition
    - raise 404 if project is not found or project doesn't belong to the current user
    """
    if request.user.is_superuser:
        project = get_object_or_404(Project, pk=project_id)
    else:
        project = get_object_or_404(Project, owner=request.user, pk=project_id)
    if request.method == "POST":
        form = ProjectForm(request.POST, instance=project)
        if form.is_valid():
            form.save()
    else:
        form = ProjectForm(instance=project)

    context = {
        'project':
        project,
        'new_application_form':
        NewApplicationForm({'project_id': project.id},
                           prefix='new_application'),
        'project_form':
        form
    }
    return render_response(request, 'project/project_view.html', context)
Пример #48
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)
Пример #49
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")
Пример #50
0
def populate_default_form(proj):
    form = ProjectForm(
        initial={
            'year': proj.year,
            'title': proj.title,
            'role': proj.role,
            'teamsize': proj.teamsize,
            'company': proj.company,
            'desc': proj.desc
        })
    return form
Пример #51
0
def project_edit(request, project_id):
    project = get_object_or_404(Project, pk=project_id)

    if request.method == "POST":
        form = ProjectForm(request.POST, instance=project)
        if form.is_valid():
            project = form.save()
            #messages.success(request, "Projects info has been saved.")
            return redirect(project_detail, project.id)
        else:
            messages.error(request, "Correct errors in the form.")
            context = RequestContext(request, {
                'form': form,
                'project': project,
                'superuser': request.user.is_superuser,
                'version_names': ['All Versions']
            })
            return render(request, 'proj/project_detail/project_detail.html', context)
    else:
        return redirect(projects)
Пример #52
0
def addproject(request):
	if request.POST:
		#files = upload_receive(request)
		form = ProjectForm(request.POST, request.FILES)
		if form.is_valid():
			f2 = form.save(commit=False)
			f2.save()
			return HttpResponseRedirect('/blog/viewprojects/')
		else:
			args = {}
			args.update(csrf(request))
			args['form']=form
			args['error']='Some error in form'
			return render_to_response('addproject.html',args)
				
	else:
		args = {}
		args.update(csrf(request))
		args['form'] = ProjectForm()
		return render_to_response('addproject.html',args)
Пример #53
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)
Пример #54
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)
Пример #55
0
def new_project(request):
    if request.method == 'POST':
        pform = ProjectForm(request.POST, instance=Project())
        if pform.is_valid():
            pform.save()
        return HttpResponseRedirect(reverse('manage_project'))
    else:
        pform = ProjectForm(instance=Project())
        context = {'project_form': pform}
        context.update(csrf(request))
        return render_to_response('viewer/project/new_project.html', context,
                                  context_instance=RequestContext(request))
Пример #56
0
def add_project(request):
    if request.method == "POST":
        form = ProjectForm(request.POST, user=request.user)
        if form.is_valid():
            form.save(request)
            messages.success(request, 'Project created successfully.')
            return HttpResponseRedirect(reverse('my_projects'))
    else:
        form = ProjectForm()
    return render_to_response('authenticated/project/add_project.html',
                              locals(),
                              context_instance=RequestContext(request))
Пример #57
0
def new_project():
    import __init__, models, forms
    from __init__ import db
    from models import Project
    from forms import ProjectForm

    project_form = ProjectForm()
    if request.method == "POST":
        if project_form.validate():
            filename = photos.save(project_form.image.data)
            #index =
            file_url = os.path.join('images/projects/', filename)
            index = (db.session.query(db.func.max(Project.index)).scalar()
                     or 0) + 1
            project = Project(title=project_form.title.data,
                              imgfile=file_url,
                              website=project_form.website.data,
                              github_url=project_form.github_url.data,
                              is_game=project_form.is_game.data,
                              description=project_form.description.data,
                              long_desc=project_form.long_desc.data,
                              index=index)

            db.session.add(project)
            print(file_url, flush=True)
            print('successfully added project', flush=True)
            db.session.commit()
            flash("Project was created.")
            return redirect(url_for("main._portfolio"))
        else:
            flash("Project creation failed.")

    return render_template("edit_form.html",
                           form=project_form,
                           title="Create Projects",
                           right=random.choice(rights),
                           new=True,
                           is_web=True)
Пример #58
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'))
Пример #59
0
def add_project(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            project = Project(owner=request.user,
                              title=form.cleaned_data['title'],
                              description=form.cleaned_data['description'],
                              nr_of_workers=form.cleaned_data['nr_of_workers'],
                              end_date=form.cleaned_data['end_date'])
            project.save()
            for s in form.cleaned_data['skills']:
                skill, created = Skill.objects.get_or_create(name=s.lower())
                if created:
                    skill.save()
                project.skills.add(skill)
                project.save()
            # print project.skills
        return redirect(reverse_lazy('projects_index'))
    else:
        form = ProjectForm()
        context_dict = {'form': form}
        return render(request, 'custom_projects/add_project.html',
                      context_dict)
Пример #60
0
def create_project_previous(request,projectId):
    context = RequestContext(request)
    user = request.user
    progress_status = 30
    project = Project.objects.get(id = projectId)
    rfp = RfpCampaign.objects.get(id = project.rfp.id)
    project_dict = model_to_dict(project)
    questions = rfp.get_project_questions()

    if request.method == 'POST':
        print (request.POST)
        #form = ProjectForm(request.POST,request.FILES, questions = questions)
        form = ProjectForm(request.POST, questions = questions)

        if form.is_valid():
            form_data = form.cleaned_data
            form_data.pop('document')

            print(form_data)
            proj_update = Project.objects.update_or_create(user = user, id = project.id, defaults=form_data)
            proj = proj_update[0]

            if request.FILES:
                proj.document = request.FILES['document']

            project = proj.save()

            if "Next" in request.POST:
                return HttpResponseRedirect(reverse('create_project_budget', args=[proj.pk]))
            else:
                return HttpResponseRedirect(reverse('create_project_previous', args=[proj.pk]))

    else:
        form = ProjectForm(initial= project_dict,questions = questions)

    return render_to_response('rfp/create_project_previous.html',{'form' : form, 'user' : user, 'progress_status' : progress_status, 'project' : project}, context)