Exemple #1
0
def add_gc(request):
    if not request.user.has_perm('app.add_gc'):
        request.session['msg'] = u'你没有权限进行此操作!'
        request.session['type'] = 'warning'
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            
            f = form.save(commit=False)
            f.user = request.user
            f.save()
            request.session['msg'] = u'成功创建工程!'
            try:
                temp = Template.objects.get(name=f.temp)
                titems = Titem.objects.filter(template=temp.pk)
                for t in titems:
                    iitem = Iitem(gc=f, key=t.key, order=t.order, parent=t.parent)
                    iitem.save()
            except Exception, e:
                request.session['msg'] += e.message
            request.session['type'] = 'success'
            
            return HttpResponseRediret('/')
        else:
            request.session['msg'] = u'创建工程失败!请检查信息是否准确填写,或是联系管理员。'
            request.session['type'] = 'danger'
            # return HttpResponse(form.errors)
        return HttpResponseRedirect('/')
 def new_project():
     if not current_user.project_id == None:
         flash(current_user.prefered_name + ' already has a project')
         return redirect(url_for('index'))
     form = ProjectForm()
     form.lab.choices = ProjectController.get_labs()
     if form.validate_on_submit():  #for post requests
         partner = Student.query.filter_by(
             id=form.partner_number.data).first()
         #illegal scenarios
         if partner is None and current_user.cits3403:
             flash('Partner not found')
             return redirect(url_for('index'))
         elif partner is not None and (partner.is_committed()
                                       or partner.id == current_user.id):
             flash(partner.prefered_name +
                   ' already has a project assigned')
             return redirect(url_for('index'))
         else:
             #check lab availability
             lab = Lab.query.filter_by(lab_id=form.lab.data).first()
             if lab is None or not lab.is_available():
                 flash("Lab not available")
             else:
                 #Everything is good, make commits
                 ProjectController.make_project(
                     form.project_description.data, lab, current_user,
                     partner)
                 return redirect(url_for("index"))
     return render_template('new_project.html',
                            student=current_user,
                            form=form)
Exemple #3
0
def create_project(username):
    user = User.query.filter_by(username=username).first_or_404()
    form = ProjectForm()
    if form.validate_on_submit():
        if form.picture.data:
            picture_file = save_project_picture(form.picture.data)
            project = Project(title=form.title.data,
                              description=form.description.data,
                              image_file=picture_file)
            db.session.add(project)
            db.session.commit()
        else:
            project = Project(title=form.title.data,
                              description=form.description.data)
            db.session.add(project)
            db.session.commit()

        # I am using advantage of the fact that projects and usesrs are a many-to-many relationship
        # So here I have to the project creator as a user that is part of this particular project
        # Further down, I do the same thing when I invite people
        # This is so we can quickly gather who is part of a project
        # This is the same logic as with a youtube channel and people subscribed to it

        project.users_in.append(user)
        json = {'id': project.id, 'sprint': 1}
        toAdd = Sprint(project_id=json["id"], sprint_num=json["sprint"])
        db.session.add(toAdd)
        db.session.commit()
        flash('You have successfully created a new project', 'success')
        return redirect(
            url_for('user_projects', username=current_user.username))
    return render_template('create_project.html',
                           title='New Project',
                           form=form,
                           legend='New Project')
Exemple #4
0
def project():
    """
    View function for the project page. It requires
    user to be logged in the system, otherwise he/she is
    redirected to login page.
    :return: HttpResponse in form of project.html template
    """

    #Setting up choices in SelectField
    form = ProjectForm()
    projects = Project.query.all()
    form.choice.choices = [(p.name, p.name) for p in projects]

    employee = Employee.query.filter_by(id=current_user.id).first()

    if form.validate_on_submit():
        choice = form.choice.data
        p = Project.query.filter_by(name=choice).first()

        #If project selected by user exists then add it to his project
        if p is not None:
            employee = Employee.query.filter_by(id=current_user.id).first()
            employee.project = p
            db.session.add(employee)
            db.session.commit()
            flash('Project Added Successfully')
        return redirect(url_for('index'))

    return render_template('project.html',
                           title='Project',
                           form=form,
                           project=employee.project)
Exemple #5
0
def project():              # this function will require testing and implementation fixes
    form = ProjectForm()
    if request.method == 'GET':
        group = load_group(current_user, request.args.get('group'))        
        try:
            project = group.get_project(request.args.get('project'))
        except ValueError as e:
            flash(e)
        if request.args.get('sub'):
            sub = project.subs.get(id=request.args.get('sub'))
        return render_template('project.html', project=project, sub=sub, form=form, processLive=group.process_live())
    elif request.method == 'POST':
        group = load_group(current_user, request.form.get('group'))                
        if request.form.get('action') == 'delete':
            if request.form.get('sub'):
                group.delete_project(request.form.get('project'), request.form.get('sub'))
            else:
                group.delete_project(request.form.get('project'))
            return redirect(url_for('account'))
        if form.validate_on_submit():
            if urlparse(form.url.data).path:
                if request.form.get('sub'):
                    group.update_project(request.form.get('project'), form, request.form.get('sub'))
                else:
                    group.update_project(request.form.get('project'), form)
            else:
                flash('URL is not valid.')
        else:
            flash_errors(form)
        query = {'group': request.form.get('group'), 'project': request.form.get('project')}
        if request.form.get('sub'):
            query['sub'] = request.form.get('sub')
        return redirect('/project' + urlencode(query))
Exemple #6
0
def edit_portfolio():

    form = ProjectForm()

    if form.validate_on_submit() and form.submit.data:

        if 'cover_img' not in request.files:
            flash('Project requires a cover photo.')
            return redirect(url_for('edit_portfolio'))

        file = request.files['cover_img']
        filename = secure_filename(file.filename)
        saved = images.save(file, folder="portfolio/")

        new_project = (PortfProject(
            name=form.name.data,
            description=form.description.data,
            url=form.url.data,
            cover_img_filename=filename,
            cover_img_alt_txt=form.cover_img_alt_txt.data,
            link_text=form.link_text.data))

        db.session.add(new_project)
        db.session.commit()

        if saved:
            flash('New project now live!')
        return redirect(url_for('portfolio'))

    projects = PortfProject.query.order_by(PortfProject.id.desc())

    return render_template('edit_portfolio.html',
                           title='Edit Portfolio',
                           form=form,
                           projects=projects)
 def edit_project():
     project = Project.query.filter_by(
         project_id=current_user.project_id).first()
     if project == None:
         flash(current_user.prefered_name + ' does not have a project yet')
         redirect(url_for('new_project'))
     team = project.get_team()
     if not team[0].id == current_user.id:
         partner = team[0]
     elif len(team) > 1:
         partner = team[1]
     else:
         partner = None
     form = ProjectForm()  #initialise with parameters
     form.lab.choices = ProjectController.get_labs(project.lab_id)
     if form.validate_on_submit():  #for post requests
         lab = Lab.query.filter_by(lab_id=form.lab.data).first()
         if lab is None or not (lab.lab_id == project.lab_id
                                or lab.is_available()):
             flash("Lab not available")
         else:
             project.description = form.project_description.data
             project.lab_id = lab.lab_id
             db.session.add(project)
             db.session.commit()
             return redirect(url_for("index"))
     return render_template('edit_project.html',
                            student=current_user,
                            partner=partner,
                            project=project,
                            form=form)
Exemple #8
0
def edit_view(request, slug):
    instance = get_object_or_404(Request, slug=slug)
    category = None
    if request.method == 'POST':
        type = request.POST['type']
        if type:
            category = get_object_or_404(RequestCategory, slug=type)
        form = ProjectForm(request.POST or None, instance=instance)
        if form.is_valid():
            project = form.save(commit=False)
            project.created_by = request.user
            if category:
                project.type = category

            project.save()
            for id in request.POST.getlist('skills'):
                tag = SkillTag.objects.get(pk=id)
                if tag:
                    project.skills.add(tag)

            project.save()
            messages.add_message(request, messages.SUCCESS, 'Your Request has been updated!')
            return HttpResponseRedirect("/projects/" + str(project.slug) + "/")
        else:
            print form.errors
    else:
        form = ProjectForm()
    return render(request=request, template_name='app/editProject.html', context={'form': form, 'instance': instance})
 def new_project():
   if not current_user.project_id==None:
     flash(current_user.prefered_name+' already has a project')
     return redirect(url_for('index'))
   form=ProjectForm()
   form.lab.choices=ProjectController.get_labs()
   if form.validate_on_submit():#for post requests
     partners=[current_user]  
     partners.append(Student.query.filter_by(id=form.partner1_number.data).first())
     partners.append(Student.query.filter_by(id=form.partner2_number.data).first())
     partners.append(Student.query.filter_by(id=form.partner3_number.data).first())
     team = [p for p in partners if p!=None]
     #illegal scenarios
     if len(team)<2:
       flash('At least two students per group')
       return redirect(url_for('index'))
     distinct = False
     for partner in team:
       if partner.is_committed():
         flash(partner.prefered_name+' already has a project assigned')
         return redirect(url_for('index'))
       if partner.id != current_user.id:
         distinct = True
     if not distinct:    
       flash('At least two students per group')
       return redirect(url_for('index'))
     #check lab availability
     lab=Lab.query.filter_by(lab_id=form.lab.data).first()
     if lab is None or not lab.is_available():
       flash("Lab not available")
       return redirect(url_for('index'))
     #Everything is good, make commits
     ProjectController.make_project(form.project_description.data,lab, team)
     return redirect(url_for("index"))
   return render_template('new_project.html', student=current_user, form=form)
Exemple #10
0
def create_project():
    form = ProjectForm()
    if form.validate_on_submit():
        project = Project(title=form.project_title.data, body=form.project.data, owner=current_user)
        db.session.add(project)
        db.session.commit()
        flash('Your project has been created')
        return redirect(url_for('index'))
    return render_template('create_project.html', title='Create Project', form=form)
Exemple #11
0
def dashboard_projects_update(project_id):
    form = ProjectForm()
    if form.validate_on_submit():
        project = save_update_project(form, project_id=project_id)
        db.session.commit()
        flash(f'Updated project "{project.title}".', "success")
        return redirect('/dashboard/projects')
    else:
        return render_template(f"dashboard/projects/{project_id}/edit.html")
Exemple #12
0
 def post(self, request):
     data = json.loads(request.body)
     form = ProjectForm(data)
     if form.is_valid():
         new_project = form.save()
         response = serializers.serialize("json", [new_project])
     else:
         response = json.dumps({'errors': form.errors})
     return HttpResponse(response, content_type="application/json")
Exemple #13
0
def dashboard_projects_store():
    form = ProjectForm()
    if form.validate_on_submit():
        project = save_update_project(form)
        db.session.add(project)
        db.session.commit()
        flash(f"Added a new project.", "success")
        return redirect('/dashboard/projects')
    else:
        return render_template("dashboard/projects.html")
Exemple #14
0
def create_project():
    form = ProjectForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        data = Project()
        form.populate_obj(data)
        data.ownerId = current_user.id
        db.session.add(data)
        db.session.commit()
        return data.to_dict()
    return ('Invalid Info')
Exemple #15
0
def add_project():
    form = ProjectForm()
    if form.validate_on_submit():
        project = Project(title=form.title.data,
                          description=form.description.data,
                          owner=current_user)
        db.session.add(project)
        db.session.commit()
        flash('New project created')
        return redirect(url_for('index'))
    return render_template('add_project.html', title='New project', form=form)
Exemple #16
0
def project_form():
    """
    Display the add project form
    :return: Flask template
    """
    form = ProjectForm()
    if form.validate_on_submit():
        flash('Project submitted for {}, is_live={}'.format(form.name.data, form.is_live.data))
        save_project(form.name.data, form.description.data, form.is_live.data)
        return redirect('/index')
    return render_template("add_project.html",title="Add New", form=form)
Exemple #17
0
def projects():
    form = ProjectForm()
    if form.validate_on_submit():
        project = Project(title=form.name.data,
                          description=form.description.data,
                          creator_id=1,
                          score=10,
                          total_funding=100)
        db.session.add(project)
        db.session.commit()
        flash('Project creation for project {}'.format(form.name.data))
        return redirect(url_for('index'))
    return render_template('form.html', title='Project Creator', form=form)
Exemple #18
0
def create_project():
    form = ProjectForm()
    if form.validate_on_submit():
        project = Project(
            unit_name=form.unit_name.data,
            proj_title=form.proj_title.data,
        )
        db.session.add(project)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('create_project.html',
                           title='Create a new project',
                           form=form)
def create_project(request):
    if not request.user.is_authenticated():
        return render(request, '/login.html')
    else:
        form = ProjectForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            project = form.save(commit=False)
            project.user = request.user
            project.save()
            jobs = Job.objects.filter(project=project)
            return render(request, 'app/project_detail.html', {'title': 'Create New Project', 'project': project, 'user': request.user, 'jobs' : jobs})

        context = {"form": form,}
        return render(request, 'app/create_project.html', context)
Exemple #20
0
def update_project(projectId):
    '''
    Updates a project's details
    '''
    project_to_update = Project.query.get(projectId)
    form = ProjectForm()
    # Do we need line below?
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        title = form.data['title']
        project_to_update.title = title

        db.session.commit()
        return {'message': 'Project Updated!'}
    return {'errors': validation_errors_to_error_messages(form.errors)}, 400
Exemple #21
0
 def _setup_forms(self):
     stack = QtGui.QStackedWidget()
     stack.addWidget(ActionForm())
     stack.addWidget(ProjectForm())
     stack.addWidget(ContextForm())
     self._stack = stack
     return stack
Exemple #22
0
def add_project():
    form = ProjectForm()
    if form.validate_on_submit():
        project = Project(
            project_title=form.project_title.data,
            professor_name=form.professor_name.data,
            email=form.email.data,
            key_words=form.key_words.data,
            project_description=form.project_description.data,
        )
        db.session.add(project)
        db.session.commit()
        return redirect('/add_project?success=true')
    return render_template('add_project.html',
                           form=form,
                           success=request.args.get('success'))
Exemple #23
0
def edit_project(request, id):
    project = get_object_or_404(Project, pk=id)

    if request.user == project.created_by or request.user.is_superuser:
        RewardTierFormSet = inlineformset_factory(
            parent_model=Project,
            model=RewardTier,
            fields=('minimum_amount', 'description'),
            extra=0,
            can_delete=project.is_draft,
        )
        if request.method == 'POST':
            form = ProjectForm(request.POST, files=request.FILES, instance=project)
            reward_tier_formset = RewardTierFormSet(request.POST, instance=project)
            if form.is_valid() and reward_tier_formset.is_valid():
                publish = request.POST.get('publish', None)
                if project.status == Project.STATUS_DRAFT and publish == '1':
                    form.instance.publish()
                form.save()
                reward_tier_formset.save()
        else:
            form = ProjectForm(instance=project)
            reward_tier_formset = RewardTierFormSet(instance=project)

        return render(request, 'app/project/edit.html', context={
            'form': form,
            'reward_tier_formset': reward_tier_formset,
            'project': project,
        })
    else:
        raise PermissionDenied()
Exemple #24
0
 def _setup_content(self):
     project_list = self._setup_projects()
     action_form = ActionForm(True)
     project_form = ProjectForm(True)
     self.addWidget(project_list)
     self.addWidget(action_form)
     self.addWidget(project_form)
     self._action_form = action_form
     self._project_form = project_form
Exemple #25
0
def add():
    form = ProjectForm()
    if form.validate_on_submit():
        project = Project(
            name=form.name.data,
            description=form.description.data,
            budget=form.budget.data,
            participants=form.participants.data,
            beginning=form.beginning.data,
            end=form.end.data,
            leader=current_user.username,
            leader_id=current_user.id,
        )
        db.session.add(project)
        db.session.commit()
        return redirect(url_for('projects'))

    
    return render_template('add.html', form=form)
def edit_project(project_id):
    """edit a Project

    :param project_id:
    :return:
    """
    project = Project.query.get(project_id)

    form = ProjectForm(request.form, project)

    if form.validate_on_submit():
        try:
            project.name = form.name.data
            db.session.add(project)
            db.session.commit()

            flash(
                "Project <strong>%s</strong> successful saved" % project.name,
                "success")

            return redirect(url_for("view_project", project_id=project.id))

        except IntegrityError as ex:
            if "UNIQUE constraint failed" in str(ex):
                msg = "Project name already in use, please use another one"

            else:
                msg = "Project was not saved (unknown error, see log for details)"

            flash(msg, "error")
            logger.error(msg, exc_info=True)
            db.session.rollback()

        except Exception:
            msg = "Project was not saved (unknown error, see log for details)"
            logger.error(msg, exc_info=True)
            flash(msg, "error")
            db.session.rollback()

    return render_template("project/edit_project.html",
                           project=project,
                           form=form)
Exemple #27
0
def add_project():
    '''
    Create a project
    '''
    form = ProjectForm()  
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        project = Project(
            # Current user didn't work...
            userId=current_user.id,
            # userId=1,
            title=form.data['title'],
            completed=False
        )
        db.session.add(project)
        db.session.commit()
        return project.to_dict()
    # This gets put into the project array
        # return {"projects": [project.to_dict() for project in projects]}
    return {'errors': validation_errors_to_error_messages(form.errors)}, 500
Exemple #28
0
def edit_project(project_id):

    form = ProjectForm()

    project = PortfProject.query.filter_by(id=int(project_id)).first_or_404()

    # update project data
    if form.validate_on_submit() and form.submit.data:

        project.name = form.name.data
        project.description = form.description.data
        project.url = form.url.data
        project.link_text = form.link_text.data
        project.cover_img_alt_txt = form.cover_img_alt_txt.data

        if 'cover_img' in request.files:

            # DELETE OLD FILE???

            file = request.files['cover_img']
            filename = secure_filename(file.filename)
            saved = images.save(file, folder="portfolio/")

            project.cover_img_filename = filename

        db.session.commit()

        if saved:
            flash('Changes saved and new image uploaded!')
        else:
            flash('Changes saved.')
        return redirect(url_for('edit_portfolio'))

    elif request.method == 'GET':
        form.name.data = project.name
        form.description.data = project.description
        form.url.data = project.url
        form.link_text.data = project.link_text
        form.cover_img_alt_txt.data = project.cover_img_alt_txt

    return render_template('edit_project.html', form=form, project=project)
Exemple #29
0
def create_project():
    form = ProjectForm()
    if form.validate_on_submit():
        new_project = Project(
            name = form.name.data,
            summary = form.summary.data,
            website = form.website.data,
            description = form.description.data,
            #future_scope = form.future_scope.data,
            short_term_goal = form.short_term_goal.data,
            category_primary = form.category_primary.data,
            category_secondary = form.category_secondary.data,
            category_tertiary = form.category_tertiary.data
        )
        usernames = tuple([name.strip() for name in form.members.data.split(',')])
        usernames = User.query.filter(User.username.in_(usernames)).all()
        new_project.contributors.extend(usernames)
        db.session.add(new_project)
        db.session.commit()
        flash("Successfully created a project")
        return redirect( url_for('leaderboard') )
    return render_template('create_project.html', title='Create Project', form=form)
Exemple #30
0
def create_project(request):
    if not request.user.is_authenticated():
        return render(request, '/login.html')
    else:
        form = ProjectForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            project = form.save(commit=False)
            project.user = request.user
            project.save()
            jobs = Job.objects.filter(project=project)
            return render(
                request, 'app/project_detail.html', {
                    'title': 'Create New Project',
                    'project': project,
                    'user': request.user,
                    'jobs': jobs
                })

        context = {
            "form": form,
        }
        return render(request, 'app/create_project.html', context)
Exemple #31
0
def create_project():
    teams = db.engine.execute('select team_name from team'
                              ' join team_user_table on (team.team_id = team_user_table.team_id)'
                              ' where team_user_table.user_id = ' + current_user.get_id())
    team_names = []
    for name in teams:
        team_names.append(name[0])

    form = ProjectForm()
    if form.validate_on_submit():
        project = Project(proj_name=form.proj_name.data, total_diff=0)
        team = Team(team_name=form.team_name.data)

        db.session.add(project)
        db.session.add(team)
        team.projteams.append(project)
        team.userteams.append(current_user)
        db.session.commit()
        flash('Congratulations, you made a project!')
        return redirect(url_for('index'))

    return render_template('CreateProjectNew.html', title='Create Project', form=form, team_names=team_names)
def edit_project(project_id):
    """edit a Project

    :param project_id:
    :return:
    """
    project = Project.query.get(project_id)

    form = ProjectForm(request.form, project)

    if form.validate_on_submit():
        try:
            project.name = form.name.data
            db.session.add(project)
            db.session.commit()

            flash("Project <strong>%s</strong> successful saved" % project.name, "success")

            return redirect(url_for("view_project", project_id=project.id))

        except IntegrityError as ex:
            if "UNIQUE constraint failed" in str(ex):
                msg = "Project name already in use, please use another one"

            else:
                msg = "Project was not saved (unknown error, see log for details)"

            flash(msg, "error")
            logger.error(msg, exc_info=True)
            db.session.rollback()

        except Exception:
            msg = "Project was not saved (unknown error, see log for details)"
            logger.error(msg, exc_info=True)
            flash(msg, "error")
            db.session.rollback()

    return render_template("project/edit_project.html", project=project, form=form)
Exemple #33
0
def dashboard_projects_edit(project_id):
    project = Project.query.get(project_id)
    if project is None:
        return "Resource not found!", 404  # todo render a 404.html
    else:
        form = ProjectForm()
        form.title.data = project.title
        form.description.data = project.description
        form.thumbnail.data = project.thumbnail
        form.hide.data = project.hide
        form.order_number.data = project.order_number
        form.link.data = project.link
        form.overlay_title.data = project.overlay_title
        form.overlay_text.data = project.overlay_text

        return render_template("dashboard/projects_edit.html", form=form, project_id=project.id)
Exemple #34
0
def start_project(request):
    RewardTierFormSet = inlineformset_factory(
        parent_model=Project,
        model=RewardTier,
        fields=('minimum_amount', 'description'),
        extra=1,
    )
    if request.method == 'POST':
        form = ProjectForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.created_by = request.user
            project = form.save()
            reward_tier_formset = RewardTierFormSet(request.POST, request.FILES, instance=project)
            if reward_tier_formset.is_valid():
                reward_tier_formset.save()
                return redirect(reverse('view_project', args=[form.instance.id]))
    else:
        form = ProjectForm()
        reward_tier_formset = RewardTierFormSet()

    return render(request, 'app/project/start.html', context={'form': form, 'reward_tier_formset': reward_tier_formset})
Exemple #35
0
def dashboard_projects_create():
    return render_template("dashboard/projects_create.html", form=ProjectForm())