Beispiel #1
0
def add_task(request):
    from forms import TaskForm
    form = TaskForm(request.POST)
    scrapy_error = False
    if form.is_valid():
        data = form.cleaned_data['data']
        print data
        mail = data['address']
        task_list = data['urls']
        http = httplib2.Http()
        data={'project':"dirbot","spider":"taobao"}
        header={'Content-Type': 'application/x-www-form-urlencoded'}
        for item in task_list:
            Q = Queue(url=item,mail=mail)
            Q.save()
            try:
                s,c = http.request("http://localhost:6800/schedule.json","POST",urlencode(data),headers=header)
            except Exception:
                c = {'status':'error','msg':'爬虫服务器连接失败'}
                scrapy_error = True
    else:
        return HttpResponse(json.dumps({'status':'error','msg':form['data'].errors}))
    if scrapy_error:
        return HttpResponse(json.dumps(c,ensure_ascii=False))
    return HttpResponse(c)
Beispiel #2
0
def add_task(request):
    # Get the context from the request.
    context = RequestContext(request)
    projectid = int(request.GET.get('projectid', '0'))
    context_dict = {}
    if request.method == 'POST':
        form = TaskForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new category to the database.
            form.save(commit=True)
            return HttpResponseRedirect('/project/view_tasks?projectid=' + str(projectid))
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
    else:
        # If the request was not a POST, display the form to enter details.
        form = TaskForm()
	
	context_dict["form"] = form
	context_dict["projectid"] = projectid

	
    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render_to_response('webapp/add_requirement.html', context_dict, context)
Beispiel #3
0
def task_create(request, id):
    milestone = get_object_or_404(Milestone, pk=id)
    if request.method == 'POST': # If the form has been submitted...
        post = request.POST.copy()
        post['milestone']=milestone.id
        form = TaskForm(data=post) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            form.save()
            # Process the data in form.cleaned_data
            # ...
            return redirect('/tasks') # Redirect after POST
    else:
        form = TaskForm(
            milestone=milestone,
            initial={
                'milestone': milestone,
                },
        )
        # An unbound form
        #from django import forms
        #form.depends_from = forms.ModelMultipleChoiceField(queryset=Task.objects.filter(milestone=milestone))
    return render(request, 'task_create.html', {
        'milestone': milestone,
        'form': form,
        })
Beispiel #4
0
def task_add_subtask(request, task_id=None, response_format='html'):
    """New subtask form"""

    parent = None
    if task_id:
        parent = get_object_or_404(Task, pk=task_id)
        if not request.user.profile.has_permission(parent, mode='x'):
            parent = None

    if request.POST:
        if 'cancel' not in request.POST:
            task = Task()
            form = TaskForm(
                request.user.profile, parent, None, None, request.POST, instance=task)
            if form.is_valid():
                task = form.save()
                task.set_user_from_request(request)
                return HttpResponseRedirect(reverse('projects_task_view', args=[parent.id]))
        else:
            return HttpResponseRedirect(reverse('projects_task_view', args=[parent.id]))
    else:
        form = TaskForm(request.user.profile, parent, None, None)

    context = _get_default_context(request)
    context.update({'form': form,
                    'task': parent})

    return render_to_response('projects/task_add_subtask', context,
                              context_instance=RequestContext(request), response_format=response_format)
Beispiel #5
0
def task_edit(request, task_id, response_format='html'):
    """Task edit page"""

    task = get_object_or_404(Task, pk=task_id)
    if not request.user.profile.has_permission(task, mode='w'):
        return user_denied(request, message="You don't have access to this Task")

    if request.POST:
        if 'cancel' not in request.POST:
            form = TaskForm(
                request.user.profile, None, None, None, request.POST, instance=task)
            if form.is_valid():
                task = form.save()
                return HttpResponseRedirect(reverse('projects_task_view', args=[task.id]))
        else:
            return HttpResponseRedirect(reverse('projects_task_view', args=[task.id]))
    else:
        form = TaskForm(
            request.user.profile, None, None, None, instance=task)

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

    return render_to_response('projects/task_edit', context,
                              context_instance=RequestContext(request), response_format=response_format)
Beispiel #6
0
def index():
	form = TaskForm()
	if form.validate_on_submit(): 
		r.table('todos').insert({"name":form.label.data}).run(g.rdb_conn)
		return redirect(url_for('index'))
	selection = list(r.table('todos').run(g.rdb_conn))
	return render_template('index.html', form = form, tasks = selection)
Beispiel #7
0
def task_add_to_milestone(request, milestone_id=None, response_format='html'):
    """Task add to preselected project"""

    milestone = None
    if milestone_id:
        milestone = get_object_or_404(Milestone, pk=milestone_id)
        if not request.user.profile.has_permission(milestone, mode='x'):
            milestone = None

    project = milestone.project
    project_id = milestone.project.id

    if request.POST:
        if 'cancel' not in request.POST:
            task = Task()
            form = TaskForm(request.user.profile, None,
                            project_id, milestone_id, request.POST, instance=task)
            if form.is_valid():
                task = form.save()
                task.set_user_from_request(request)
                return HttpResponseRedirect(reverse('projects_task_view', args=[task.id]))
        else:
            return HttpResponseRedirect(reverse('projects_milestone_view', args=[milestone.id]))
    else:
        form = TaskForm(
            request.user.profile, None, project_id, milestone_id)

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

    return render_to_response('projects/task_add_to_milestone', context,
                              context_instance=RequestContext(request), response_format=response_format)
Beispiel #8
0
    def test_task_form(self):
        data = {
            "title": "Write some tests",
            "day": "01/04/2005",
            "start_time": 2,
            "end_time": 2,
            "user": self.alice.pk,
            "project": self.project.pk,
            "status": Project.ACTIVE,
            "task_type": self.et.pk,
        }
        form = TaskForm(data)
        self.assertFalse(form.is_valid())

        data["start_time"] = 11
        data["count"] = 3
        form = TaskForm(data)
        self.assert_(form.is_valid())
        tt = TaskType.objects.create(title="why?")
        task = form.save(commit=False)
        task.task_type = tt
        task.author = self.alice
        task.save()
        task.add_occurrences(
            form.cleaned_data["start_time"], form.cleaned_data["end_time"], count=form.cleaned_data["count"]
        )
        self.assertEqual(Occurrence.objects.count(), 3)
Beispiel #9
0
def edit_task_in_list(request, storyID, taskID):
    story = mdl_story.get_story(storyID)
    task = mdl_task.get_task(taskID)
    project = story.project
    association = UserAssociation.objects.get(
        user=request.user,
        project=project)
    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            task = form.save(commit=True)
    else:
        form = TaskForm(instance=task)
    tasks = mdl_task.get_tasks_for_story(story)

    context = {
        'story': story,
        'tasks': tasks,
        'task': task,
        'editform': form,
        'project': project,
        'association': association
    }

    return render(request, 'TaskList.html', context)
Beispiel #10
0
    def post(self, request):
        form = TaskForm(data=request.POST)
        if not form.is_valid():
            return self.get(request, form)

        form.save()
        return redirect('index')
Beispiel #11
0
def create_task(request):
	
	if request.method == "POST":
		f = TaskForm(request.POST)
		if f.is_valid():
			c = f.save(commit=False)
			c.CreatedOn = timezone.now()
			c.CreatedBy = request.user
			c.LastUpdatedOn = timezone.now()
			c.LastUpdatedBy = request.user
			
			c.save()
	
			messages.success(request, "Your Task was added")
			return HttpResponseRedirect('/persons/all')
	else:
		f = TaskForm()
	args = {}
	args.update(csrf(request))
	
	
	args['form'] = f
	
	return render_to_response('create_task.html', args)

		
	
	message.add_message(request, settings.DELETE_MESSAGE, "Your task was deleted successfully")
	return HttpResponseRedirect('/persons/all' % person_id)
Beispiel #12
0
def tasks():
	# imported our TaskForm class, instantiated an object from it,
	#and sent it down to the template where forms is used.
	form = TaskForm(request.form)
	tasks = Task.query.all()
	# for task in tasks:
	# 	db.session.delete(task)
	# db.session.commit()

	if request.method == 'POST' and form.validate_on_submit():
		flash('Created Async Task!')
		#save numberOfSeconds in a session hash
		session['numberOfSeconds'] = form.numberOfSeconds.data
		time = int(session['numberOfSeconds'])
		#START OF ASYNC SLEEP CALL#
		t1 = start_sleep.delay(time)
		session['TASK_ID'] = t1.id
		#add new async task to database
		new_task = Task(time = int(session['numberOfSeconds']),status= t1.ready(),key =session['TASK_ID'])
		db.session.add(new_task)
		db.session.commit()
		return redirect(url_for('tasks'))
	return render_template('tasks.html',
					title = 'Amadeus Task', 
					form = form,
					tasks = tasks)
Beispiel #13
0
def task():
	form = TaskForm()
	if request.method == "POST":
		if form.validate() == False:
			flash("All fields are required")
			return render_template("task.html",form=form)
		else:
			
			task_name = form.name.data
			task_client = form.client.data
			task_capabilities = form.capabilities.data
			task_duration = int(form.duration.data)
			#insert values to Task table
				
			task_msg = task_insert(task_name,task_client,task_capabilities,task_duration)
				
                         
			
			return jsonify(name =task_name,
					client=task_client, 
					capabilities=task_capabilities,
					duration=task_duration,result = task_msg)
			#return render_template("success.html",form=form)
	elif request.method == 'GET':
		return render_template("task.html",form=form)
Beispiel #14
0
 def test_should_be_invalid_from_blank_description(self):
     """
     A Task Form should be invalid, due to blank desc.
     """
     task = Task()
     task_form = TaskForm(instance=task)
     self.assertFalse(task_form.is_valid())
Beispiel #15
0
def new_task():
    form = TaskForm(request.form)
    if request.method == 'POST' and form.validate():
        task = Task(form.name.data, form.text.data, form.memory.data, form.time_limit.data, g.user)
        task.save()
        return redirect(url_for('task', task_id=task.task_id))

    return render_template('task_form.html', form=form)
Beispiel #16
0
def update_task(request, id):
    task = Tasks.objects.get(pk=id)
    form = TaskForm(request.POST or None, instance=task)
    if request.POST:
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        return render(request, 'create_task.html', {'form': form})
def index():
	form = TaskForm()
	if form.validate_on_submit(): # if it is a POST request
		task = Task(label = form.label.data)
		task.save()
		return redirect(url_for('index'))
	
	tasks = Task.objects.all()
	return render_template('index.html', form = form, tasks = tasks)
Beispiel #18
0
def new_task(request):
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = TaskForm()
    return render(request, 'create_task.html', {'form': form})
Beispiel #19
0
def get_task_list_task(request):
    t_l_id = None
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/new_task_list/')
    else:
        form = TaskForm()
    return render(request, "tasks_add.html", { 'form': form , 't_l_id':t_l_id})
Beispiel #20
0
def addtask(request):
    if request.POST:
            form = TaskForm(request.POST)
            if form.is_valid():
                form.save()
                messages.success(request, 'Task added!')
                return HttpResponseRedirect('/tasks/')
    else:
        form = TaskForm()

    return render(request, 'addtask.html', locals())
Beispiel #21
0
def update(request, project_slug, task_id):
    project = Project.get_by_slug(request.user, project_slug)
    task = get_object_or_404(Task, pk=task_id, project=project)
    form = TaskForm(request.POST, instance=task)
    if form.is_valid():
        task = form.save()
        tre = TaskRegexp()
        due_date = tre.get_date(task.title)
        task.due_date = due_date
        task.save()
        return HttpResponse(dumps(dict(html=task.html)))
Beispiel #22
0
def home(request):
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            request = Request('me','www.baidu.com')
            re = request.start()
            return HttpResponse( re)
    else:
        form = TaskForm()
    return render_to_response('home.html',{'form':form }, RequestContext(request))
Beispiel #23
0
def task_form(request):
    context = RequestContext(request)
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/tasks/')
        else:
            print(form.errors)
    else:
        form = Task()
    return render_to_response('tasks/index.html', {'form': form}, context)
Beispiel #24
0
    def post(self, request, task_id):
        form = TaskForm(request.POST, instance=Task.objects.get(pk=task_id))

        if form.is_valid():
            form.save()
            messages.add_message(request, messages.INFO, "Task updated!")
            return redirect("/task/%s/" % task_id)

        print form.errors

        context = {'form': form}
        return render(request, self.template_name, context)
Beispiel #25
0
def addtask(request):
    if request.method == 'POST': # If the form has been submitted...
        form = TaskForm(request.POST) # A form bound to the POST data
        if form.is_valid():
            task = form.cleaned_data['task']
            newtask = tasks(task=task)
            newtask.save()
            return HttpResponseRedirect('/tasks/')
        else:
            return HttpResponse("Here's the tex.")
    else:
        return HttpResponse("Here's the text.")
Beispiel #26
0
    def post(self, request):
        form = TaskForm(request.POST)

        if form.is_valid():
            form.save()
            messages.add_message(request, messages.INFO, "Task created!")
            return redirect("/list/%s/" % list_id)

        print form.errors

        context = {'form': form}
        return render(request, self.template_name, context)
Beispiel #27
0
def edit_task(request):
    task = Task.objects.get(id=request.POST.get('id'))
    copy = request.POST.copy()
    copy['user'] = request.user.id
    form = TaskForm(copy, instance=task)
    if form.is_valid():
        form.save()
        messages.add_message(request, messages.SUCCESS,
                             'Task has been updated!')
    else:
        messages.add_message(request, messages.ERROR,
                             'Error: Task is not updated!')
    return HttpResponseRedirect(reverse('task:tasks'))
Beispiel #28
0
def edit_task(request, t_id):
    task = Task.objects.get(id=t_id)
    # instance ={'title':task.title,'body':task.body,'priority':task.priority }
    # form = EditTForm(initial={'title':task.title,'body':task.body,'priority':task.priority})
    form = TaskForm(request.POST or None, instance= task)
    # form = TaskForm(initial={'title':instance.title,'body':instance.body,'priority':instance.priority,'dead_line':instance.dead_line,'note':instance.note,'pub_date':instance.pub_date})
    if form.is_valid():
        # task.title=form.cleaned_data['title']
        # task.body=form.cleaned_data['body']
        # task.priority=form.cleaned_data['priority']
        form.save()
        return HttpResponseRedirect('/')
    return render(request,"task_edit.html",{'form':form})
Beispiel #29
0
def edit_task(task_id):
    task = Task.query.get(task_id)
    if g.user.user_id != task.author_id:
        flash('You do not have proper authorization to do this!', 'danger')
        return redirect('/task/' + str(task_id))

    form = TaskForm(obj=task)
    if request.method == 'POST' and form.validate():
        form = TaskForm(request.form)
        form.populate_obj(task)
        task.save()
        return redirect(url_for('task', task_id=task.task_id))

    return render_template('task_form.html', form=form, edit=True)
Beispiel #30
0
def todo(request):
    context = RequestContext(request)
    tasks = Task.objects.all
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/todo/')
        else:
            print(form.errors)
    else:
        form = Task()

    return render_to_response('tasks/TODO.html', {'tasks': tasks, 'form': form}, context)
Beispiel #31
0
def todo_edit(*args, **kwargs):
    user = kwargs.get('user')
    id = kwargs.get('id')
    current_task = Task.query.get_or_404(id)
    form = TaskForm(
        content=current_task.content,
        status=current_task.status
    )
    if form.validate_on_submit():
        current_task.content = form.content.data
        current_task.status = form.status.data

        db.session.add(current_task)
        db.session.commit()
        flash('Your Task has been updated!')
        return redirect(url_for('todo_list'))
    return render_template('todo/add.html', form=form, title='Edit Task | TodoApp')
Beispiel #32
0
def add_task():
    """
    print(task.errors) 表单校验错误
    print(task.validate_on_submit()) 判断是否是一个有效的post请求
    print(task.validate()) 判断是否是一个合法的post请求
    print(task.data) 提交的数据
    """
    errors = ""
    task = TaskForm()
    if request.method == "POST":
        if task.validate_on_submit():  # 判断是否是一个有效的post请求
            formData = task.data
        else:
            errors_list = list(task.errors.keys())
            errors = task.errors
            print(errors)
    return render_template("add_task.html", **locals())
Beispiel #33
0
def todo_add(*args, **kwargs):
    user = kwargs.get('user')
    form = TaskForm()
    if form.validate_on_submit():
        field_content = form.content.data
        field_status = int(form.status.data)
        task = Task(content=field_content,
                    status=field_status,
                    user_id=user.id)
        db.session.add(task)
        db.session.commit()
        flash('Task has been added!')
        return redirect(url_for('todo_list'))

    return render_template('todo/add.html',
                           form=form,
                           title="Add Task | TodoApp")
Beispiel #34
0
def edit_task(t_id):
    task, tags = get_task(t_id)
    form = TaskForm(name=task['name'],
                    statement=task['statement'],
                    short_statement=task['short_statement'],
                    todo=task['todo'],
                    tutorial=task['tutorial'],
                    complexity=task['complexity'],
                    source=task['source'])

    form.set_choices()

    if form.validate_on_submit():
        d = _to_dict(form)
        d['tags'] = [t['tag'] for t in d['tags']]
        update_task(d, t_id)
        return redirect(url_for('render_task', t_id=t_id))

    if tags != []:
        form.tags.pop_entry()

        for tag in tags:
            t = Tag()
            t.set_choices()
            t.tag = tag['id']
            t.csrf_token = form.csrf_token
            form.tags.append_entry(t)

    form.set_choices()

    return render_template(form.template,
                           form=form,
                           name="Редактировать задачу")
Beispiel #35
0
def task_add(request):
    #从TaskForm获取相关信息
    form = TaskForm(request.POST or None)
    if form.is_valid():
        #建立一个task实例
        task_ins = Task()
        #通过时间来建立一个任务流水
        task_ins.task_code = str(int(time.time()))
        #获取task的相关信息
        task_ins.task_title = form.cleaned_data.get('task_title')
        task_ins.task_category = form.cleaned_data.get('task_category')
        task_ins.task_contacts = form.cleaned_data.get('task_contacts')
        #task建立后默认变成处理中的状态
        task_ins.task_status = '处理中'
        #通过登录用户来辨别任务登记人
        task_ins.task_signer = request.user
        #保存task实例
        task_ins.save()
        #通过当前task_id获取task对象,并将其赋给member_task
        member_task = Task.objects.get(id=task_ins.id)
        #获取members集合
        members = form.cleaned_data.get('task_member')
        #获取members集合中的member,并将其添加到member_task中,增添相应实施人员
        for member in members:
            member_task.task_member.add(member)

        #通过task_id获取task对象
        process_task = Task.objects.get(id=task_ins.id)
        #建立一个process的实施步骤实例
        process_ins = Process()
        #将process实例与task绑定
        process_ins.task = process_task
        #获取process相关信息
        process_ins.process_content = form.cleaned_data.get('process_content')
        process_ins.process_signer = request.user
        process_ins.save()

        return redirect('task_list')

    context = {
        'form': form,
        'page_title': '任务处理',
        'sub_title': '新建任务',
    }
    return render(request, 'task_add.html', context)
Beispiel #36
0
def add_todo():
    form = TaskForm()
    if form.validate_on_submit():
        dt_date = dateutil.parser.parse(form.date_due.data)
        if dt_date.hour == 0 and dt_date.minute == 0:
            str_date = dt_date.strftime("%d/%m/%Y")
        else:
            str_date = dt_date.strftime("%H:%M on %d/%m/%Y")
        new_task = TDList3(
            task=form.task.data,
            date_due=dt_date,
            date_due_str=str_date,
            completed=form.completed.data
        )
        db.session.add(new_task)
        db.session.commit()
        return redirect(url_for("todo"))
    return render_template("add_todo.html", form=form)
def targets():
    print(request)
    print(request.method)
    tasks = genmai_tasks.query.filter_by(user_id=current_user.id).all()
    for task in tasks:
        print(task.id)
    print(tasks)
    form = TaskForm()
    return render_template('back/targets.html', form=form, tasks=tasks)
Beispiel #38
0
def edit_todo(task_id):
    task_to_edit = TDList3.query.get(task_id)
    form = TaskForm(
        task=task_to_edit.task,
        date_due=task_to_edit.date_due
    )
    if form.validate_on_submit():
        dt_date = dateutil.parser.parse(form.date_due.data)
        if dt_date.hour == 0 and dt_date.minute == 0:
            str_date = dt_date.strftime("%d/%m/%Y")
        else:
            str_date = dt_date.strftime("%H:%M on %d/%m/%Y")
        task_to_edit.task = form.task.data
        task_to_edit.date_due = dt_date
        task_to_edit.date_due_str = str_date
        task_to_edit.completed = form.completed.data
        db.session.commit()
        return redirect(url_for("todo"))
    return render_template("add_todo.html", form=form)
Beispiel #39
0
def edit_task(id):
    check_admin()
    add_task = False
    task = Task.query.get_or_404(id)
    form = TaskForm(obj=task)
    if form.validate_on_submit():
        task.name = form.name.data
        task.service = form.service.data
        task.component = form.component.data
        task.description = form.description.data
        task.yaml_name = form.yaml_name.data
        task.ss_bundle = form.ss_bundle.data
        task.recommendation = form.recommendation.data
        task.show_results = form.show_results.data

        db.session.commit()
        flash('You have successfully edited the task.')
        return redirect(url_for('admin.list_tasks'))

    return add_edit_form_template("Edit", "Task", form)
Beispiel #40
0
def editTask(task_id):
    form = TaskForm()
    task = db.session.query(taskDB).filter_by(id=task_id).one()
    if form.validate_on_submit():
        task.title = form.title.data.strip()
        task.note = form.note.data.strip()
        task.start_time = form.start_time.data.strip()
        task.duration = form.duration.data
        task.finish_time = finishTime(task.start_time, task.duration)
        db.session.add(task)
        db.session.commit()
        return redirect(url_for('home'))
    form.note.data = task.note
    form.title.data = task.title
    form.start_time.data = task.start_time
    form.duration.data = task.duration
    return render_template('edittask.html',
                           form=form,
                           task=task,
                           today=present_date)
Beispiel #41
0
def create():
	form = TaskForm()
	if request.method == 'POST':
		newtask = Task(form.title.data, form.description.data)
		db.session.add(newtask)
		db.session.commit()
		return "Success!"
	elif request.method == 'GET':
		tasks = Task.query.all()
		# return render_template("layout.html", tasks=tasks)
		return jsonify({'tasks': tasks_schema.dump(tasks).data})	
Beispiel #42
0
def add_task_into_list(request, storyID):
    story = mdl_story.get_story(storyID)
    project = story.project
    association = UserAssociation.objects.get(user=request.user,
                                              project=project)
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            mdl_task.create_task(story, request.POST)
    else:
        form = TaskForm()
    tasks = mdl_task.get_tasks_for_story(story)
    context = {
        'story': story,
        'tasks': tasks,
        'newform': form,
        'project': project,
        'association': association
    }
    return render(request, 'TaskList.html', context)
Beispiel #43
0
def remove_task_from_list(request, storyID, taskID):
    story = mdl_story.get_story(storyID)
    task = mdl_task.get_task(taskID)
    if request.method == 'POST':
        task.delete()
    tasks = mdl_task.get_tasks_for_story(story)
    form = TaskForm()

    context = {'story': story, 'tasks': tasks, 'newform': form}

    return render(request, 'TaskList.html', context)
Beispiel #44
0
def modify_task(task_id):
    form = TaskForm()
    task_ = Task.query.get(task_id)
    if task_ is None:
        flash(f'Нет таска с id={task_id}', 'danger')
        return redirect(url_for('main'))
    form.author.choices = [(u.id, u.username) for u in User.query.all()]
    if form.validate_on_submit():
        for u in task_.solved:
            u.points -= (task_.points - form.points.data)
        for u in task_.authors:
            u.points -= (task_.points - form.points.data)
        task_.task = form.name.data
        task_.description = form.description.data.replace('\r\n', '\n')
        task_.category = form.category.data
        task_.points = form.points.data
        task_.link = form.link.data or None
        task_.authors = [User.query.get(user_id) for user_id in form.author.data]
        task_.flag = form.flag.data
        task_.is_hidden = form.is_hidden.data
        for file in request.files.getlist('files'):
            filename = secure_filename(file.filename)
            base_dir = (Path(app.static_folder) / f'files/tasks/{task_.id}').resolve()
            base_dir.mkdir(parents=True, exist_ok=True)
            file.save(str(base_dir / filename))
            db_file = TaskFiles(file=filename)
            db.session.add(db_file)
            task_.files.append(db_file)
        db.session.commit()
        flash('Таск изменён!', 'success')
        return redirect(url_for('task', task_id=task_id))
    form.name.data = task_.task
    form.description.data = task_.description or ''
    form.category.data = task_.category
    form.points.data = task_.points
    form.link.data = task_.link or ''
    form.author.data = [user.id for user in task_.authors]
    form.flag.data = task_.flag
    form.is_hidden.data = task_.is_hidden
    return render_template('admin_task.html', form=form, task=task_, new=False,
                           flag_pattern=app.config.get('FLAG_REGEXP', ''))
Beispiel #45
0
def update_task(itsid, path_to_redirect):
    task = Task.query.get_or_404(itsid)
    if task.author != current_user:
        abort(403)
    form = TaskForm()

    if form.validate_on_submit():
        task.title = form.title.data
        task.lastdate = form.lastdate.data
        task.note = form.note.data
        db.session.commit()
        flash("Task Updated Successfully!", 'success')
        return redirect(url_for(path_to_redirect))
    elif request.method == "GET":
        form.title.data = task.title
        form.lastdate.data = task.lastdate
        form.note.data = task.note
    return render_template("create_task.html",
                           title='Update Task',
                           form=form,
                           legend='Update')
Beispiel #46
0
    def update_task_form(task_id):
        # sends the task_form.html page with title of "Update Task"
        task = Task.query.get(task_id)
        form = TaskForm(obj=task)

        # get all volunteers in name order for volunteer choices in form
        form.volunteer_id.choices = get_volunteer_choices()

        return render_template('task_form.html',
                               form=form,
                               task=task,
                               title="Update Task")
Beispiel #47
0
def add_task():
    check_admin()

    form = TaskForm()
    if form.validate_on_submit():
        task = Task(name=form.name.data,
                    service=form.service.data,
                    component=form.component.data,
                    description=form.description.data,
                    yaml_name=form.yaml_name.data,
                    ss_bundle=form.ss_bundle.data,
                    recommendation=form.recommendation.data,
                    show_results=form.show_results.data)
        try:
            db.session.add(task)
            db.session.commit()
            flash('You have successfully added a new task.')
        except:
            flash('Error: task name already exists.')
        return redirect(url_for('admin.list_tasks'))
    return add_edit_form_template("Add", "Task", form)
def edit_task_in_list(request, storyID, taskID):
    story = mdl_story.get_story(storyID)
    task = mdl_task.get_task(taskID)
    project = story.project
    association = UserAssociation.objects.get(
        user=request.user,
        project=project
    )
    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            task = form.save(commit=True)
    else:
        form = TaskForm(instance=task)
    tasks = mdl_task.get_tasks_for_story(story)

    context = {
        'story': story,
        'tasks': tasks,
        'task': task,
        'editform': form,
        'project': project,
        'association': association
    }

    return render(request, 'TaskList.html', context)
Beispiel #49
0
def edit_task(project_key, task_key):
    form = TaskForm(request.form)
    project = Project.get_project(project_key)
    if project is None:
        abort(404)
    task = Task.get_task(project, task_key)
    choices = [(p.id, p.name) for p in project.people]
    form.assigned_to.choices = choices
    if request.method == 'POST' and form.validate():
        flash("Task was updated")
        task.update(form.title.data, int(form.priority.data),
                    form.description.data, form.assigned_to.data)
        return redirect(
            url_for('view_task', project_key=project_key, task_key=task_key))
    form.title.data = task.title
    form.priority.data = str(task.priority)
    form.description.data = task.description
    form.assigned_to.data = task.assigned_to
    return render_template('edit_task.html',
                           task=task,
                           project=project,
                           form=form)
Beispiel #50
0
def addtask(request):
    if request.POST:
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Task added!')
            return HttpResponseRedirect('/tasks/')
    else:
        form = TaskForm()

    return render(request, 'addtask.html', locals())
Beispiel #51
0
def edit_task(request, bid=None, tid=None):
    """ Edit/GET and save/POST a task entity for a backlog item.
        User permission required: add_backlog
    """
    if tid:
        task = get_object_or_404(Task, pk=tid)
        backlog = task.item
    elif bid:
        backlog = get_object_or_404(Backlog, pk=bid)
        task = None
    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            tsk = form.save(commit=False)
            if not hasattr(tsk, 'item'):
                setattr(tsk, 'item', backlog)
            try:
                tsk.save()
                #form.save_m2m()
            except Exception, e:
                logger.error('edit_task form.save failure %s' % e)
            return HttpResponseRedirect('/backlog/%s/tasks' % backlog.pk)
Beispiel #52
0
def tasks():

    if 'userid' in session:
        user = User.query.get_or_404(session['userid'])

        if request.method == 'POST':
            form = TaskForm(request.form)
            if form.validate():
                newtask = Task(form.title.data, user, None, form.value.data)
                db.session.add(newtask)
                db.session.commit()
                return redirect(url_for('tasks'))
            else:
                tasks = user.tasks.filter(Task.complete == False).order_by(
                    desc(Task.dateadded)).all()
                return render_template('tasks.html',
                                       username=user.username,
                                       points=user.points,
                                       tasks=tasks,
                                       form=form,
                                       idform=TaskIdForm(),
                                       updateform=TaskUpdateForm(),
                                       containerclass="listcontainer")

        else:
            tasks = user.tasks.filter(Task.complete == False).order_by(
                desc(Task.dateadded)).all()
            return render_template('tasks.html',
                                   username=user.username,
                                   points=user.points,
                                   tasks=tasks,
                                   form=TaskForm(),
                                   idform=TaskIdForm(),
                                   updateform=TaskUpdateForm(),
                                   containerclass="listcontainer")
    # if no session, display default home page. TODO: convert to splash page
    else:
        return redirect(url_for('front'))
Beispiel #53
0
def index_bak(request):
    if request.user.is_authenticated():
        forms = TaskForm()
        pwd_forms = ChangeForm()
        template = loader.get_template('review.html')
        context = {
            "task": "active",
            "forms": forms,
            "pwd_forms": pwd_forms,
            "username": request.user.username
        }
        return HttpResponse(template.render(context, request))
    else:
        return HttpResponseRedirect('/login/')
Beispiel #54
0
def _get_task_suite_form():
    """
    :return : TaskForm
    Task form with log folders as file choice
    """
    folders = _sort_by_folder(
        File.query.filter_by(stored=True).order_by(File.name).all())
    return TaskForm(file_choices=[(folder, os.path.split(folder)[1])
                                  for folder in folders],
                    sw_choices=[
                        (sw.name, sw.name)
                        for sw in Software.query.order_by(Software.name).all()
                    ],
                    prefix='suite')
Beispiel #55
0
def tasks():
    form = TaskForm()

    if request.method == 'POST':

        task_details = request.form

        task_name = task_details['task_name']
        project = task_details['project']
        assignee = task_details['assignee']
        due_date = task_details['due_date']
        status = task_details['status']
        task_description = task_details['task_description']
        notag = re.sub("<.*?>", " ", task_description)

        cur = mysql.connection.cursor()
        cur.execute(
            "INSERT INTO `task`(`Task_Name`, `Task_description`, `Due_Date`, `Status`, `Project_Name`, `Assignee`) VALUES (%s, %s, %s, %s, %s, %s)",
            (task_name, notag, due_date, status, project, assignee))
        mysql.connection.commit()

        flash('Task added successfully!')
        cur.close()

        assignee = "%" + request.form['assignee'] + "%"

        cur = mysql.connection.cursor()
        cur.execute(
            f"SELECT `Email` FROM `user` WHERE `userName` LIKE '{assignee}'")
        recipient = cur.fetchone()
        cur.close()

        cur = mysql.connection.cursor()
        resultvalue = cur.execute(
            " SELECT * FROM `task` WHERE `Task_Name` = %s", (task_name, ))

        if resultvalue > 0:
            taskDetail = cur.fetchall()
            cur.close()

            msg = Message('APMT',
                          sender='*****@*****.**',
                          recipients=[recipient['Email']])
            #msg.body = "Hi,\n.\n\n"
            msg.html = render_template('mail.html', taskDetail=taskDetail)
            mail.send(msg)

        return redirect(url_for('tableList'))
    else:
        return render_template('task.html', form=form)
def add_task():
    print('add_task')
    form = TaskForm()
    print(form.validate_on_submit())
    print(request.method)
    if request.method == 'POST' and form.validate_on_submit():
        if current_user.id is None:
            abort(404)
        user = genmai.query.filter_by(id=current_user.id).first()
        if user is None:  # 因为没有设置外建,所以这里一定要去查询一下
            abort(404)

        # TODO: 检测一下输入是否合法
        if test_inject_sql_username_string(
                request.form['asin']) and test_inject_sql_username_string(
                    request.form['seller']):
            flash('不合法的输入,请勿尝试注入')
            return redirect('/')

        new_task = genmai_tasks(user_id=user.id,
                                asin=request.form['asin'],
                                country=request.form['country'],
                                seller=request.form['seller'],
                                youxian=request.form['youxian'])
        db.session.add(new_task)
        db.session.commit()

        print(current_user.id)
        print(current_user.username)
        print(request.form)
        print(request.form['asin'])
        print(request.form['country'])
        print(request.form['seller'])
        print(request.form['youxian'])
        return redirect(url_for('targets'))
    else:
        abort(404)
Beispiel #57
0
def todo_list(*args, **kwargs):
    user = kwargs.get('user')
    task_list = Task.query.filter_by(user_id=user.id).all()
    return render_template('todo/list.html', data_list=task_list, title="Ta Do List | TodoApp"
    

@app.route('/todos/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def todo_edit(*args, **kwargs):
    user = kwargs.get('user')
    id = kwargs.get('id')
    current_task = Task.query.get_or_404(id)
    form = TaskForm(
        content=current_task.content,
        status=current_task.status
    )
    if form.validate_on_submit():
        current_task.content = form.content.data
        current_task.status = form.status.data
        db.session.add(current_task)
        db.session.commit()
        flash('Your Task has been updated!')
        return redirect(url_for('todo_list'))
    return render_template('todo/add.html', form=form, title='Edit Task | TodoApp')


@app.route('/todos/delete/<int:id>', methods=['GET','POST'])
def todo_delete(*args, **kwargs):
    id = kwargs.get('id')
    current_task = Task.query.get_or_404(id)
    form = DeleteForm()
    if form.validate_on_submit():
        db.session.delete(current_task)
        db.session.commit()
        flash('Your Task has been deleted!')
        return redirect(url_for('todo_list'))
    return render_template('todo/del.html', form=form, title='Delete Task | TodoApp')
Beispiel #58
0
def _get_task_log_form():
    """
    :return : TaskForm
    Task form with log files as file choice
    """
    files = [
        file.name for file in File.query.filter_by(
            stored=True).order_by(File.name).all()
    ]
    return TaskForm(file_choices=list(zip(files, files)),
                    sw_choices=[
                        (sw.name, sw.name)
                        for sw in Software.query.order_by(Software.name).all()
                    ],
                    prefix='log')
Beispiel #59
0
def add(week_id):
    """Add a new task record for each task item."""
    f = TaskForm()
    # print(f.data)
    if f.validate_on_submit():
        if f.prep_dev.data:
            new_task = Tasks(week_id=week_id, prep_dev=f.prep_dev.data)
            db.session.add(new_task)
        if f.prep_doc.data:
            new_task = Tasks(week_id=week_id, prep_doc=f.prep_doc.data)
            db.session.add(new_task)
        if f.review_dev.data:
            new_task = Tasks(week_id=week_id, review_dev=f.review_dev.data)
            db.session.add(new_task)
        if f.review_task.data:
            new_task = Tasks(week_id=week_id, review_task=f.review_task.data)
            db.session.add(new_task)
        if f.review_doc.data:
            new_task = Tasks(week_id=week_id, review_doc=f.review_doc.data)
            db.session.add(new_task)
        db.session.commit()
    # else:
    #     print('validation failed')
    return redirect(url_for('worksheet.worksheet', week_id=week_id))
Beispiel #60
0
def list_tasks(request, storyID):
    story = mdl_story.get_story(storyID)
    project = story.project
    association = UserAssociation.objects.get(user=request.user,
                                              project=project)
    tasks = mdl_task.get_tasks_for_story(story)
    form = TaskForm()
    context = {
        'story': story,
        'tasks': tasks,
        'newform': form,
        'project': project,
        'association': association
    }
    return render(request, 'TaskList.html', context)