Exemplo n.º 1
0
    def test_task_fromdict_dependencies(self):
        user = self.create_user()

        task1 = Task(user=user, description='test')
        task1.save(track=False)
        task2 = Task(user=user, description='test2')
        task2.save(track=False)

        data = {
            'description': 'foobar',
            'uuid': 'sssssssss',
            'status': 'pending',
            'entry': '12345',
            'user': user,
            'annotation_1324076995': u'this is an annotation',
            'depends': u','.join([t.uuid for t in (task1, task2)]),
            'priority': '',
        }

        task = Task.fromdict(data)

        # ensure the data is in the db, not just the task
        # object from above
        task = Task.objects.get(description='foobar')
        self.assertEqual(list(Undo.objects.all()), [])
        data.pop('user')
        data.pop('priority')
        self.assertEqual(data, task.todict())
Exemplo n.º 2
0
 def test_mark_task_done(self):
     user = self.create_user()
     task = Task(description='test', user=user)
     task.save()
     self.assertEqual(task.status, 'pending')
     task.done()
     self.assertEqual(task.status, 'completed')
Exemplo n.º 3
0
def create(request):
    if request.method == 'POST':
        form = TaskCreateForm(request.POST)
        if form.is_valid():
            thisadmin = MyAdmin.objects.get(user_id=request.user.user_id)

            schema_name = request.POST.get('TaskDataTableName', '')
            schema = request.POST.get('TaskDataTableScheme', '')

            cursor = connection.cursor()
            cursor.execute(schema)
            cursor.close()

            tskobj = Task(task_name=request.POST.get('Name', ''),
                          admin=thisadmin,
                          description=request.POST.get('Comment', ''),
                          mincycle=request.POST.get('mincycle', ''))
            tskobj.save()

            task_schema = TaskSchema(task_id=tskobj,
                                     TaskDataTableName=schema_name,
                                     TaskDataTableScheme=schema)
            task_schema.save()

            return redirect('taskdatatableschema')
        #return redirect('/pjadmin')
        return render(request, 'TaskCreateFail.html')
    else:
        form = TaskCreateForm()

    return render(request, 'TaskCreate.html', {'form': form})
Exemplo n.º 4
0
def create_task(request, template_pk):
    """提交创建任务表单"""
    if not request.user.is_authenticated:
        return redirect(reverse('login'))
    template = get_object_or_404(Template, pk=template_pk)

    task = Task(user=request.user, template=template)
    try:
        task.set_name(request.POST['inputTaskName'])
        split_arg = task.set_args({
            param.name: request.POST[param.name]
            for param in template.param_set.all()
        })
    except ValueError as e:
        return JsonResponse({
            'status': 'ERROR',
            'message': e.args[0]
        },
                            json_dumps_params={'ensure_ascii': False})
    task.save()
    task_arg = task.args_dict()
    for i in range(split_arg):
        task_arg[template.split_param] = i + 1
        Job.objects.create(uuid=uuid.uuid4(),
                           task=task,
                           args=json.dumps(task_arg))
    return JsonResponse({
        'status': 'SUCCESS',
        'tasks': get_recent_tasks(request.user)
    })
Exemplo n.º 5
0
    def post(self, request, *args, **kwargs):
        form = TaskAddForm(request.POST)
        user = request.user

        if form.is_valid():
            task = Task(
                name=form.cleaned_data["name"],
                task_status=form.cleaned_data["task_status"],
                start_date=form.cleaned_data["start_date"],
                start_time=form.cleaned_data["start_time"],
                # users=(user,)
            )
            try:
                task.save()
                task.users.add(user)
            except Exception as e:
                return HttpResponse(render(request, "task/task_list.html", {"form": form}))

            return HttpResponseRedirect(reverse("task_list"))
        else:
            tasks_list = user.task_set.all().order_by("-id")
            paginator = MyPaginator(tasks_list, per_page=5, max_range=3)
            tasks = paginator.page(1)
            return render(request, "task/task_list.html", {
                "form": form,
                "tasks": tasks,
            })
Exemplo n.º 6
0
 def test_mark_task_done(self):
     user = self.create_user()
     task = Task(description='test', user=user)
     task.save()
     self.assertEqual(task.status, 'pending')
     task.done()
     self.assertEqual(task.status, 'completed')
Exemplo n.º 7
0
def task_display(request, pk):
	if request.method == 'POST':
		form = TaskForm(request.POST)
		user = request.user if request.user.is_authenticated else None
		if form.is_valid():
			task = Task(
				tasklist_id = pk,
				description=request.POST['description'],
				created=timezone.now(),
				creator=user,
				)
			task.save()
			return redirect('task:task_display', pk)

	task_list = get_object_or_404(TaskList, pk=pk)
	user = request.user if request.user.is_authenticated else None
	tasks = task_list.tasks.filter(creator=user)
	length = task_list.count()
	complete_length = task_list.count_complete()
	incomplete_length = task_list.count_incomplete()
	if length != 0:
		progress = round((complete_length/length)*100, 0)
	else:
		progress = 0
	context = {
		'task_list':task_list,
		'tasks':tasks,
		'len':length,
		'complete':complete_length,
		'incomplete':incomplete_length,
		'progress':progress,
		'form':TaskForm(),
		}
	return render(request, 'task/tasks.html', context)
Exemplo n.º 8
0
def complete_task(request, pk, list_id):
	task = Task(id = pk, tasklist_id=list_id)
	task.description = Task.objects.get(pk=pk).description
	task.is_complete = True
	task.completed_at = timezone.now()
	task.save()
	return redirect('task:task_display', list_id)
Exemplo n.º 9
0
def restart_task(request, pk, list_id):
	task = Task(id = pk, tasklist_id=list_id)
	task.description = Task.objects.get(pk=pk).description
	task.is_complete = False
	task.completed_at = None
	task.save()
	return redirect('task:task_display', list_id)
Exemplo n.º 10
0
    def post(self, request, *args, **kwargs):
        form = TaskAddForm(request.POST)
        user = request.user

        if form.is_valid():
            task = Task(
                name=form.cleaned_data["name"],
                task_status=form.cleaned_data["task_status"],
                start_date=form.cleaned_data["start_date"],
                start_time=form.cleaned_data["start_time"],
                # users=(user,)
            )
            try:
                task.save()
                task.users.add(user)
            except Exception as e:
                return HttpResponse(
                    render(request, "task/task_list.html", {"form": form}))

            return HttpResponseRedirect(reverse("task_list"))
        else:
            tasks_list = user.task_set.all().order_by("-id")
            paginator = MyPaginator(tasks_list, per_page=5, max_range=3)
            tasks = paginator.page(1)
            return render(request, "task/task_list.html", {
                "form": form,
                "tasks": tasks,
            })
Exemplo n.º 11
0
    def execute(self):
        task = Task()
        task.project = self.payload.get('project')
        task.title = self.payload.get('title')
        task_type = self.payload.get('task_type')
        task.task_type = task_type
        task.label = self.payload.get('label')
        task.priority = self.payload.get('priority')
        task.branch = Task.generate_branch()
        assignee = self.payload.get('assignee')
        if assignee:
            task.assignee = assignee
        if task_type == TaskChoices.SUB_TASK:
            task.parent = self.payload.get('parent')  # it must be instance

        task.deadline = self.payload.get('deadline')
        task.descriptions = self.payload.get('descriptions')
        created_by = self.payload.get('created_by')
        task.created_by = created_by
        task.save()
        if assignee != created_by:
            # send email & notifications to user if he not assignee task to himself

            title = f'{created_by.username} assigned an task to you.'
            payload = {
                'title': title,
                'recipient': assignee.id,
                'subject': ASSIGNEE_TASK,
                'related_data': task.id
            }
            NotificationTask.task_push_notification.delay(payload)
        return task
Exemplo n.º 12
0
    def test_task_fromdict_dependencies(self):
        user = self.create_user()

        task1 = Task(user=user, description='test')
        task1.save(track=False)
        task2 = Task(user=user, description='test2')
        task2.save(track=False)

        data = {'description': 'foobar', 'uuid': 'sssssssss',
                'status': 'pending',
                'entry': '12345',
                'user': user,
                'annotation_1324076995': u'this is an annotation',
                'depends': u','.join([t.uuid for t in (task1, task2)]),
                'priority': '',
                }

        task = Task.fromdict(data)

        # ensure the data is in the db, not just the task
        # object from above
        task = Task.objects.get(description='foobar')
        self.assertEqual(list(Undo.objects.all()), [])
        data.pop('user')
        data.pop('priority')
        self.assertEqual(data, task.todict())
Exemplo n.º 13
0
 def test_create_task_undo(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     self.assertEqual(len(Undo.objects.all()), 1)
     self.assertNotIn('old', Undo.serialize())
     self.assertEqual(len(Undo.serialize().splitlines()), 3)
     task.delete()
Exemplo n.º 14
0
 def test_create_task_undo(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     self.assertEqual(len(Undo.objects.all()), 1)
     self.assertNotIn('old', Undo.serialize())
     self.assertEqual(len(Undo.serialize().splitlines()), 3)
     task.delete()
Exemplo n.º 15
0
def create(request):
    if request.method == 'GET':
        return render(request, 'task/create.html')
    elif request.method == 'POST':
        text = request.POST.get('title')
        task = Task(text=text, creator=request.user)
        task.save()
        return redirect(todo_list)
Exemplo n.º 16
0
Arquivo: views.py Projeto: yask123/api
def index(request):
    if request.method == 'GET':
        name = request.GET.get('name', '')
        location = request.GET.get('location')
        acc_token = request.GET.get('token')
        if location:
            geolocator = Nominatim()
            location = geolocator.geocode(location)
            location = str(location.latitude) + ',' + str(location.longitude)
        else:
            lat = request.GET.get('lat')
            lon = request.GET.get('lon')
            location = str(lat) + ',' + str(lon)

        print name, location, acc_token

        if acc_token:
            graph = GraphAPI(acc_token)
        else:
            graph = GraphAPI(
                'CAACEdEose0cBAPJRZA8xHkMmbokHYBCUyjcKxZBohVhzJnGlm2ETlOYESQpEjG1Gj6ykTV4FMmhqMUrgFsJp0HdH4TszHwCkoMA8PS8L2MRFth3w3Wm7ucx4xMglc9ZBZAMhnyrr3XNAlH6MHZBtGmeWusWvzu4GSt4Mt9oS2KIOkWh70WhQ3ktOUC40PgChklQN31X0EgAZDZD'
            )

        search = name
        search = qp(search)

        result = graph.get('search?type=place&q=' + search + '&center=' +
                           location)
        page_id = result['data'][0]['id']

        params = 'fields=phone,likes,current_location,about,website,food_styles,description,hours,awards,price_range,location,booking_agent,is_verified,offers,public_transit,founded,products,emails,parking'
        a = str(page_id) + '?' + params
        cache = {}
        cache['facebook'] = {}
        cache['google'] = {}

        cache['facebook'] = {'fb_page_url': 'http://facebook.com/' + page_id}
        params = params.split(',')
        for each in params:
            try:
                cache['facebook'][each] = str(graph.get(a)[each])
            except:
                pass

#Google Data
        url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + location + '&radius=5000&name=' + name + '&key=AIzaSyDAERlVmOrLWdq0pHF5fK3c2cHmCSvy55I'
        print url
        r = requests.get(url)
        google_result = json.loads(r.text)
        cache['google'] = google_result

        return HttpResponse(json.dumps(cache), content_type="application/json")

    elif request.method == 'POST':
        t = request.POST.get("task", "")
        a = Task(text=t, date=timezone.now())
        a.save()
        return redirect('/')
Exemplo n.º 17
0
    def test_pending_tasks(self):
        user = self.create_user()
        task = Task(description='test, test', user=user)
        task.save()
        self.assertEqual(len(Task.objects.all()), 1)

        response = self.client.get('/pending/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.context['datagrid'].rows), 1)
Exemplo n.º 18
0
 def test_task_is_dirty_m2m(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     self.assertTrue(task._is_dirty())
     task.save()
     self.assertFalse(task._is_dirty())
     task.tags.add(Tag.objects.create(tag='foobar'))
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['tags'])
     self.assertTrue(task._is_dirty())
Exemplo n.º 19
0
 def test_create_task_with_uuid(self):
     """ Verify that when instantiating a Task with a uuid specified,
         it uses that uuid.
     """
     user = self.create_user()
     uuid = 'foobar'
     task = Task(description='my description', uuid=uuid, user=user)
     task.save()
     self.assertEqual(task.uuid, uuid)
Exemplo n.º 20
0
 def test_task_is_dirty_foreign_key(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     self.assertTrue(task._is_dirty())
     task.save()
     self.assertFalse(task._is_dirty())
     task.priority = Priority.objects.get(weight=1)
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['priority'])
     self.assertTrue(task._is_dirty())
Exemplo n.º 21
0
 def test_task_saving_without_data_change(self):
     """ Make sure that saving a task twice without
         a change in data doesn't create duplicate Undo's
     """
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     task.save()
     self.assertEqual(len(Undo.objects.all()), 1)
Exemplo n.º 22
0
 def test_task_saving_without_data_change(self):
     """ Make sure that saving a task twice without
         a change in data doesn't create duplicate Undo's
     """
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     task.save()
     self.assertEqual(len(Undo.objects.all()), 1)
Exemplo n.º 23
0
 def test_task_is_dirty_foreign_key(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     self.assertTrue(task._is_dirty())
     task.save()
     self.assertFalse(task._is_dirty())
     task.priority = Priority.objects.get(weight=1)
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['priority'])
     self.assertTrue(task._is_dirty())
Exemplo n.º 24
0
 def test_create_task_with_uuid(self):
     """ Verify that when instantiating a Task with a uuid specified,
         it uses that uuid.
     """
     user = self.create_user()
     uuid = 'foobar'
     task = Task(description='my description', uuid=uuid, user=user)
     task.save()
     self.assertEqual(task.uuid, uuid)
Exemplo n.º 25
0
    def test_pending_tasks(self):
        user = self.create_user()
        task = Task(description='test, test', user=user)
        task.save()
        self.assertEqual(len(Task.objects.all()), 1)

        response = self.client.get('/pending/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.context['datagrid'].rows), 1)
Exemplo n.º 26
0
 def test_task_is_dirty_m2m(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     self.assertTrue(task._is_dirty())
     task.save()
     self.assertFalse(task._is_dirty())
     task.tags.add(Tag.objects.create(tag='foobar'))
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['tags'])
     self.assertTrue(task._is_dirty())
Exemplo n.º 27
0
 def test_create_task_no_uuid(self):
     """ Verify that a `Task`s uuid field is automatically populated
         when not specified.
     """
     # description and user are the only required field
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     self.assertTrue(hasattr(task, 'uuid'))
     self.assertNotEqual(task.uuid, None)
Exemplo n.º 28
0
 def test_create_task_no_uuid(self):
     """ Verify that a `Task`s uuid field is automatically populated
         when not specified.
     """
     # description and user are the only required field
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     self.assertTrue(hasattr(task, 'uuid'))
     self.assertNotEqual(task.uuid, None)
Exemplo n.º 29
0
    def test_task_tags_single_tag(self):
        user = self.create_user()
        task = Task(description='foobar', user=user)
        task.save()

        # single tag
        tag = Tag.objects.create(tag='django')
        task.tags.add(tag)
        task.save()
        self.assertEqual(list(task.tags.all()), [tag])
Exemplo n.º 30
0
    def test_task_tags_single_tag(self):
        user = self.create_user()
        task = Task(description='foobar', user=user)
        task.save()

        # single tag
        tag = Tag.objects.create(tag='django')
        task.tags.add(tag)
        task.save()
        self.assertEqual(list(task.tags.all()), [tag])
Exemplo n.º 31
0
def index(request):
	if request.method == 'GET':
		a = Task.objects.all().order_by('date').reverse()
		context ={'tasks':a}
		return render(request,'task/index.html',context)
	elif request.method == 'POST':
		t =  request.POST.get("task", "")
		a = Task(text=t,date=timezone.now())
		a.save()
		return redirect('/')
Exemplo n.º 32
0
def index(request):
    if request.method == 'GET':
        a = Task.objects.all().order_by('date').reverse()
        context = {'tasks': a}
        return render(request, 'task/index.html', context)
    elif request.method == 'POST':
        t = request.POST.get("task", "")
        a = Task(text=t, date=timezone.now())
        a.save()
        return redirect('/')
Exemplo n.º 33
0
 def test_task_is_dirty(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['user', 'description'])
     self.assertTrue(task._is_dirty())
     task.save()
     self.assertFalse(task._is_dirty())
     self.assertItemsEqual(task._get_dirty_fields().keys(), [])
     task.description = 'foobar2'
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['description'])
     self.assertTrue(task._is_dirty())
Exemplo n.º 34
0
    def test_task_tags_multiple_tags(self):
        user = self.create_user()
        task = Task(description='foobar', user=user)
        task.save()

        # multiple tags
        tag1 = Tag.objects.create(tag='spam')
        tag2 = Tag.objects.create(tag='eggs')
        task.tags.add(tag1, tag2)
        task.save()
        self.assertEqual(list(task.tags.all()), [tag1, tag2])
Exemplo n.º 35
0
def create(request):
    if request.method =='GET':
        return render(request,'task/create.html')
    elif request.method =='POST':
        text = request.POST.get('title')

        task = Task(text=text,creator=request.user)  # 很重要的一点, creator =request.user

        # 创建模型的时候,创建了两个参数:text,creator,
        task.save()
        return redirect(list)
Exemplo n.º 36
0
    def test_task_tags_multiple_tags(self):
        user = self.create_user()
        task = Task(description='foobar', user=user)
        task.save()

        # multiple tags
        tag1 = Tag.objects.create(tag='spam')
        tag2 = Tag.objects.create(tag='eggs')
        task.tags.add(tag1, tag2)
        task.save()
        self.assertEqual(list(task.tags.all()), [tag1, tag2])
Exemplo n.º 37
0
 def create_task(self, type, application, document):
     task=Task()
     task.type = type
     task.application = application
     if type == 'createdocument':
         task.document = document
     elif type == 'classifydocument':
         task.classify = document
     else:
         raise Exception('Not a valid task type.')
     task.save()
Exemplo n.º 38
0
 def test_edit_task_undo(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     task.annotate('annotation')
     self.assertEqual(len(Undo.objects.all()), 2)
     self.assertIn('old', Undo.serialize())
     # 'old' shouldn't have an annotation
     new_undo = Undo.objects.get(pk=2)
     self.assertNotIn('annotation_', new_undo.old)
     self.assertEqual(len(Undo.serialize().splitlines()), 7)
     self.assertNotIn('annotation_', Undo.serialize().splitlines()[4])
Exemplo n.º 39
0
 def test_task_is_dirty(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     self.assertItemsEqual(task._get_dirty_fields().keys(),
                           ['user', 'description'])
     self.assertTrue(task._is_dirty())
     task.save()
     self.assertFalse(task._is_dirty())
     self.assertItemsEqual(task._get_dirty_fields().keys(), [])
     task.description = 'foobar2'
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['description'])
     self.assertTrue(task._is_dirty())
Exemplo n.º 40
0
 def test_edit_task_undo(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     task.annotate('annotation')
     self.assertEqual(len(Undo.objects.all()), 2)
     self.assertIn('old', Undo.serialize())
     # 'old' shouldn't have an annotation
     new_undo = Undo.objects.get(pk=2)
     self.assertNotIn('annotation_', new_undo.old)
     self.assertEqual(len(Undo.serialize().splitlines()), 7)
     self.assertNotIn('annotation_', Undo.serialize().splitlines()[4])
Exemplo n.º 41
0
def new_task(request):
    name = unicode.strip(request.POST.get('name'))
    description = unicode.strip(request.POST.get('description'))
    pk = request.POST.get('pk')
    if pk:
        task = Task.objects.get(pk=pk)
        task.name = name
        task.description = description
    else:
        task = Task(name=name, description=description)
    task.save()
    return HttpResponseRedirect(reverse('tasks'))
Exemplo n.º 42
0
def new_task(request):
    name = unicode.strip(request.POST.get('name'))
    description = unicode.strip(request.POST.get('description'))
    pk = request.POST.get('pk')
    if pk:
        task = Task.objects.get(pk=pk)
        task.name = name
        task.description = description
    else:
        task = Task(name=name, description=description)
    task.save()
    return HttpResponseRedirect(reverse('tasks'))
Exemplo n.º 43
0
    def create(self, validated_data):
        classifier = super(ClassifierSerializer, self).create(validated_data)
        application = Application.objects.filter(id=validated_data['application_id']).first()

        # Create a task to finish the work
        task=Task()
        task.type = 'createclassifier'
        task.application = application
        task.classifier = classifier
        task.save()

        return classifier
Exemplo n.º 44
0
def new(request):
    resp = {}
    if request.method != 'POST':
        resp['status'] = 1
        resp['message'] = 'Wrong http method!'
        return HttpResponse(json.dumps(resp), content_type = 'application/json')
    approximate_fplace = request.POST['approximate_fplace']
    detailed_fplace = request.POST['detailed_fplace']
    pto = request.POST['pto']
    code = request.POST['code']
    fetch_btime = request.POST['fetch_btime']
    fetch_etime = request.POST['fetch_etime']
    owner = request.POST['owner']
    give_time = request.POST['give_time']
    curtime = datetime.datetime.now()
    user = User.objects.filter(id = owner)
    if not user.exists():
        resp['status'] = 1
        resp['message'] = 'No such user'
        return HttpResponse(json.dumps(resp), content_type = 'application/json')
    elif len(user) > 1:
        resp['status'] = 2
        resp['message'] = 'Too many user found, impossible!'
        return HttpResponse(json.dumps(resp), content_type = 'application/json')

    if user[0].status == 0:
        resp['status'] = 3
        resp['message'] = 'Not authenticated yet!'
        return HttpResponse(json.dumps(resp), content_type='application/json')

    if user[0].bonus <= 0:
        resp['status'] = 4
        resp['message'] = 'You do not have enough bonus!'
        return HttpResponse(json.dumps(resp), content_type='application/json')

    task = Task(approximate_fplace = approximate_fplace, detailed_fplace = detailed_fplace,
                pto = pto, code = code, fetch_btime = datetime.datetime.strptime(fetch_btime, '%Y-%m-%d %H:%M:%S'),
                fetch_etime = datetime.datetime.strptime(fetch_etime, '%Y-%m-%d %H:%M:%S'), owner = user[0],
                give_time = datetime.datetime.strptime(give_time, '%Y-%m-%d %H:%M:%S'), build_time = curtime)
    task.save()
    if task.id is None:
        resp['status'] = 4
        resp['message'] = 'create task error'
        return HttpResponse(json.dumps(resp), content_type = 'application/json')
    else:
        user[0].bonus -= 1
        user[0].save()
        resp['status'] = 0
        resp['message'] = 'Success'
        info = task.to_dict()
        info['owner'] = task.owner.to_dict()
        resp['data'] = info
        return HttpResponse(json.dumps(resp), content_type = 'application/json')
Exemplo n.º 45
0
    def create(self, validated_data):
        docset = super(DocSetSerializer, self).create(validated_data)
        application = Application.objects.filter(id=validated_data['application_id']).first()

        # Create a task to finish the work
        task=Task()
        task.type = 'createdocset'
        task.application = application
        task.docset = docset
        task.save()

        return docset
Exemplo n.º 46
0
def tasks_new_view(request):
	#TODO - check permissions
	try:
		o = Task(	project=Project.objects.get(id=request.GET['project']),
					title=request.GET['title'],
					type=request.GET['type'],
					severity=request.GET['severity'],
					description=request.GET['description'],
					created_by=request.user)
		o.save()
	except:
		return HttpResponse("Something went wrong!")
	return HttpResponse("1")
Exemplo n.º 47
0
 def post(self, request):
     """ Adding a new task. """
     serializer = TaskSerializer(data=request.DATA)
     if not serializer.is_valid():
         return Response(serializer.errors, status=
             status.HTTP_400_BAD_REQUEST)
     else:
         data = serializer.data
         owner = request.user
         t = Task(owner=owner,description=data['description'], done=False,due_date=data['due_date'])
         t.save()
         request.DATA['id'] = t.pk # return id
         return Response(data, status=status.HTTP_201_CREATED)
Exemplo n.º 48
0
def save_task_in_db(json, user):
    from task.models import Task
    for i in json:
        try:
            Task.objects.get(w_url=i['url'])
        except:
            print('Saving')
            t = Task()
            t.title = i['title']
            t.content = i['desc']
            t.w_desc = i['desc']
            t.w_url = i['url']
            t.user = user
            t.save()
Exemplo n.º 49
0
def create_task(request):
	context_dict = {}
	employee = Employee.objects.get(pk=1)
	if request.user.is_authenticated():
		username = request.user.username
		employee = Employee.objects.get(user=request.user)
		context_dict['employee'] = employee
	if request.method == 'POST':
		title = request.POST['title']
		desc = request.POST['desc']
		date = request.POST['date']
		today = datetime.now().date()
		task = Task(owner=employee, date_published=today, date_due=date, title=title, description=desc, state=False)
		task.save()
	return render(request, 'task/create_task.html', context_dict)
Exemplo n.º 50
0
def savetask(request):
    print "Inside task creation"
    pid = request.POST['data1']
    task = request.POST['task']
    task_desc = request.POST['task_desc']
    sdate = request.POST['sdate']
    edate = request.POST['edate']
    assignee = request.POST['assigne']
    user = request.user
    get_project = Projects.objects.get(id=int(pid))
    get_assignee = User.objects.get(username=assignee)
    create_task = Task(project=get_project, user=user, task=task, task_desc=task_desc, completed=False, start_date=sdate, end_date=edate, assigned_to=get_assignee, created=timezone.now())
    create_task.save()
    response = { 'message': 'Task Saved' }
    return HttpResponse(response)
Exemplo n.º 51
0
def create_task_with_goal(args, goal_id):
    print("ran2")
    arg_dict = json.loads(args)
    deadline_string = arg_dict["deadline"]
    deadline_list = deadline_string.split('-')
    day = int(deadline_list[0])
    month = int(deadline_list[1])
    year = int(deadline_list[2])
    task = Task(description=arg_dict["task"],\
                deadline=date(year, month, day),\
                done=arg_dict["done"],\
                goal=Goal.objects.get(pk=goal_id),\
                user=None)
    task.user = None
    task.save()
    return task.inJson()
Exemplo n.º 52
0
	def createTask(self,dc,war):
		print('createTask')
		server = Server.objects.get(id=dc.serverId)
		task = Task()
		task.serverId = dc.serverId
		task.host = server.host
		task.applicationId = dc.applicationId
		task.dcId = dc.id
		task.warPath = war
		task.deployAS = dc.deployAS
		task.md5val = ''
		task.deployPath = dc.deployPath
		task.shell = dc.shell
		task.status=0
		task.createTime=datetime.datetime.now()
		task.save()
Exemplo n.º 53
0
def add_task(request, template='task/add.html'):
    if request.method == 'POST':
        task = Task(user=request.user)
        form = forms.TaskForm(request.POST, instance=task)
        if form.is_valid():
            task = form.save()
            # silly extra save to create
            # undo object for m2m fields
            task.save()
            return HttpResponseRedirect('/')
    else:
        form = forms.TaskForm(initial={'user': request.user})

    context = {
                'method': 'add',
                'form': form,
                'title': "Add Task",
                }
    return render(request, template, context)
Exemplo n.º 54
0
    def test_task_form(self):
        user = self.create_user()
        tags = Tag.objects.create(tag='tag1')
        task = Task()
        d = {'priority': '', 'description': 'foobar',
                'user': '******', 'tags': ['1'],
                'status': 'pending'}
        form = forms.TaskForm(d)
        valid = form.is_valid()
        self.assertTrue(valid)
        task = form.save()

        # silly extra save() to
        # add proper undo info for m2m
        task.save()

        tdict = task.todict()
        self.assertEqual(tdict['description'], 'foobar')
        self.assertEqual(Undo.objects.count(), 2)
Exemplo n.º 55
0
def new(request):
    no_form = True
    if request.method == 'POST':
        form = newForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            content = form.cleaned_data['content']
            user = request.user
            x = Task(name=name, content=content, author=user)
            x.save()
            return HttpResponseRedirect('/task/new/finish/')
    else:
        form = newForm()
    
    return render_to_response('task_new.html', {
        'form': form,
        },
        context_instance=RequestContext(request),
    )
Exemplo n.º 56
0
def get_mock_task(project, owner,
                  is_reviewed=False, is_accepted=False, is_closed=False,
                  solution=None):
    """ Generate task.

    :return Task:

    """
    t = Task(
        title="A task by %s" % owner.username,
        owner=owner,
        project=project,
        parent=solution,
        is_reviewed=is_reviewed,
        time_reviewed=timezone.now() if is_reviewed else None,
        is_accepted=is_accepted,
        is_closed=is_closed,
        time_closed=timezone.now() if is_closed else None,
    )
    t.save()
    return t
Exemplo n.º 57
0
def create_tasks_from_json(description):
    """
    Given a list of Task description dictionaries, create Task instances,
    together with other related objects.

    Supported special data:
        _content (string) - the text of the task, MathContent text
        _folder_id (int) - ID of the folder where to add the task
        _folder_position (int) - position in that folder
        _tags (string) - a comma-separated list of tags
        _difficulty (int) - difficulty rating to be assigned by the author
        _permissions (dict {"permission type ID": [list of group IDs]})
                - group permission to automatically assign.
                - (ID is a string because in JSON keys must be strings)

    All other elements with an underscore are ignored.

    Params:
        description (list): list of dict object, describing the tasks

    Returns:
        A list of the new Task objects.

    If an exception is thrown in the middle of the process, the exception is
    caputed, the message changed, and raised again.
    """
    # Approx.
    task_fields = set(Task._meta.get_all_field_names())
    task_fields |= set(x + '_id' for x in task_fields)

    created_objects = []
    created_tasks = []
    message_list = []

    # List of objects to create
    folder_tasks = []
    object_permissions = []

    try:
        for k, desc in enumerate(description):
            message_list.append('Creating {}. task...'.format(k + 1))

            # First, prepare data to be able to create Task.
            # --- math content ---
            math_content = MathContent()
            math_content.text = desc['_content']
            message_list.append(desc['_content'])
            math_content.save()
            created_objects.append(math_content)

            # Second, create Task.
            task = Task()
            task.content = math_content
            for key, value in desc.iteritems():
                if key[0] != '_' and key in task_fields:
                    setattr(task, key, value)
            task.save()
            created_objects.append(task)
            created_tasks.append(task)

            # Third, save other data.

            # --- tags ---
            tags = desc.get('_tags', '')
            set_tags(task, tags)

            # --- difficulty ---
            difficulty = desc.get('_difficulty')
            if difficulty:
                task.difficulty_rating.update(task.author, int(difficulty))

            # --- folder ids ---
            folder_id = desc.get('_folder_id')
            if folder_id is not None:
                folder_tasks.append(FolderTask(
                        folder_id=folder_id, task=task,
                        position=desc.get('_folder_position', 0)))

            # --- group permissions ---
            for perm, group_ids in desc.get('_permissions', {}).iteritems():
                for group_id in group_ids:
                    object_permissions.append(ObjectPermission(
                            content_object=task, group_id=group_id,
                            permission_type=perm))


        FolderTask.objects.bulk_create(folder_tasks)
        ObjectPermission.objects.bulk_create(object_permissions)
    except Exception as e:
        # This should remove all dependend objects.
        for obj in created_objects:
            obj.delete()

        message_list.append("Reverting changes...")
        message = "\n".join(message_list) + "\n\n" + traceback.format_exc()
        raise type(e)(message)
    finally:
        # SPEED: Don't invalidate everything.
        invalidate_cache_for_folders(Folder.objects.all())
    return created_tasks
Exemplo n.º 58
0
 def test_create_task_save_without_track(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save(track=False)
     self.assertEqual(len(Undo.objects.all()), 0)
Exemplo n.º 59
0
 def test_task_tags_empty(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     self.assertEqual(list(task.tags.all()), [])