Esempio n. 1
0
def task_create(request):
    if request.method == "GET":
        if request.user.role == "ADMIN" or request.user.is_superuser:
            users = User.objects.filter(is_active=True).order_by("email")
            accounts = Account.objects.filter(status="open")
        # elif request.user.google.all():
        #     users = []
        #     accounts = Account.objects.filter(created_by=request.user).filter(status="open")
        else:
            users = User.objects.filter(role="ADMIN").order_by("email")
            accounts = Account.objects.filter(
                Q(created_by=request.user) | Q(assigned_to__in=[request.user])
            ).filter(status="open")
        form = TaskForm(request_user=request.user, request_obj=request)
        return render(
            request,
            "task_create.html",
            {
                "form": form,
                "users": users.filter(company=request.company),
                "accounts": accounts.filter(company=request.company),
                "teams": Teams.objects.filter(company=request.company),
            },
        )

    if request.method == "POST":
        form = TaskForm(request.POST, request_user=request.user, request_obj=request)
        if form.is_valid():
            task = form.save(commit=False)
            task.created_by = request.user
            task.company = request.company
            task.save()
            task.assigned_to.add(*request.POST.getlist("assigned_to"))
            task.contacts.add(*request.POST.getlist("contacts"))

            if request.POST.getlist("teams", []):
                user_ids = Teams.objects.filter(
                    id__in=request.POST.getlist("teams")
                ).values_list("users", flat=True)
                assinged_to_users_ids = task.assigned_to.all().values_list(
                    "id", flat=True
                )
                for user_id in user_ids:
                    if user_id not in assinged_to_users_ids:
                        task.assigned_to.add(user_id)

            if request.POST.getlist("teams", []):
                task.teams.add(*request.POST.getlist("teams"))

            kwargs = {"domain": request.get_host(), "protocol": request.scheme}
            assigned_to_list = list(task.assigned_to.all().values_list("id", flat=True))
            send_email.delay(task.id, assigned_to_list, **kwargs)
            success_url = reverse("tasks:tasks_list")
            if request.POST.get("from_account"):
                success_url = reverse(
                    "accounts:view_account", args=(request.POST.get("from_account"),)
                )
            return JsonResponse({"error": False, "success_url": success_url})
        else:
            return JsonResponse({"error": True, "errors": form.errors})
Esempio n. 2
0
def add_project_task(request,slug):
    if request.user.is_authenticated():
        project = Project.objects.get(slug = slug)
        if request.POST:
            form = TaskForm(request.POST)
            if form.is_valid():
                data = form.cleaned_data
                td = data['end_date'] - data['start_date']
                if td.total_seconds()>0:
                    task = Task()
                    task.name = data['name']
                    task.description = data['description']
                    task.start_date = data['start_date']
                    task.end_date = data['end_date']
                    task.user = data['user']
                    task.project = project
                    task.save()
                else:
                    messages.add_message(request, messages.ERROR,
                        " end date is less than start date!")
                    return (redirect(reverse('Task:add_task')))
                return (redirect(reverse('Home:manager')))
            else:
                messages.add_message(request, messages.ERROR, 
                    "invalid form")
                return (redirect(reverse('Task:add_task')))
        else:
            form = TaskForm()
            send_dict={}
            context_instance=RequestContext(request)
            send_dict['project'] = project
            send_dict['form'] = form
            return render_to_response('tasks/add_task.html',send_dict,context_instance)
    else:
        return redirect(reverse('Login:login'))
Esempio n. 3
0
def task_create(request):
    if request.method == 'GET':
        if request.user.role == 'ADMIN' or request.user.is_superuser:
            users = User.objects.filter(is_active=True).order_by('email')
        elif request.user.google.all():
            users = []
        else:
            users = User.objects.filter(role='ADMIN').order_by('email')
        form = TaskForm(request_user=request.user)
        return render(request, 'task_create.html', {
            'form': form,
            'users': users
        })

    if request.method == 'POST':
        form = TaskForm(request.POST, request_user=request.user)
        if form.is_valid():
            task = form.save(commit=False)
            task.created_by = request.user
            task.save()
            task.assigned_to.add(*request.POST.getlist('assigned_to'))
            task.contacts.add(*request.POST.getlist('contacts'))
            kwargs = {'domain': request.get_host(), 'protocol': request.scheme}
            send_email.delay(task.id, **kwargs)
            return JsonResponse({
                'error': False,
                'success_url': reverse('tasks:tasks_list')
            })
        else:
            return JsonResponse({'error': True, 'errors': form.errors})
Esempio n. 4
0
def edit(request, task_id):
    # if this is a POST request we need to process the form data

    current_user = request.user
    controller = TaskController(current_user.id)
    task = controller.get_task_by_id(task_id)

    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = TaskForm(request.POST)
        # check whether it's valid:

        if form.is_valid():
            data = form.cleaned_data
            controller.edit_task(
                task_id, {
                    'title': data['title'],
                    'text': data['text'],
                    'status': data['status'],
                    'tags': data['tags']
                })
            return HttpResponseRedirect('/tasks')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = TaskForm(data=task)

    return render(request, 'tasks/edit-task.html', {
        'form': form,
        'task': task
    })
Esempio n. 5
0
def tasks_edit(request, id):
  """
  Edit a task 
  """
  try:
    
    task = Task.objects.get(user=request.user, id=id)
    
    if request.method == 'POST':
      form = TaskForm(request.POST) 
      if form.is_valid(): 
        # update task 
        data = form.cleaned_data
        task.task = data.get('task')
        task.notes = data.get('notes')
        task.priority = data.get('priority')
        task.save()
        # set message 
        messages.add_message(request, messages.SUCCESS, 'Task updated')
        return redirect('url_tasks')
    else:
      form = TaskForm(instance=task)

    return render_to_response('tasks/edit.html', 
                              { 'task': task, 
                                'form' : form }, 
                    context_instance=RequestContext(request)) 
    
  except Task.DoesNotExist:
    pass
    
  raise Http404
Esempio n. 6
0
def tasks(request):
	context = {}
	utc=pytz.UTC
	nowtime = utc.localize(datetime.now())

	if request.method == 'POST':
		form = TaskForm(request.POST)
		if form.is_valid():
			task = form.save()
			record = {'id': task.id, 'title': task.title, 
				'edate': dateformat.format(task.expiration_date, 'F j, Y, P')}
			data = {'status': 'ok', 'messageType': 'addTask', 'record': record}
		else:
			data = {'status': 'error', 'messageType': 'showErrors', 'record': form.errors}
		return 	HttpResponse(simplejson.dumps(data), content_type='application/json')	
	else:		
		form = TaskForm()

	context['form'] = form
	tasks = Task.objects.filter(is_deleted = False)

	for task in tasks:
		if task.is_expired == False and task.expiration_date < nowtime:
			task.is_expired = True
			task.save()
	context['tasks'] = tasks

	return render_to_response('tasks/tasks.html', context, 
		context_instance=RequestContext(request))
Esempio n. 7
0
def test_form_data(title, description, validity):
    form = TaskForm(data={
        'title': title,
        'description': description,
    })

    assert form.is_valid() is validity
Esempio n. 8
0
def project(request, pk):
	try:
		project = Project.objects.get(pk=pk)
	except Project.DoesNotExist:
		return HttpResponseRedirect("/tasks/")
	if request.user == project.user:  # or request.user in project.team:
		if request.method == "POST":
			form = TaskForm(request.POST)
			if form.is_valid():
				task = form.save(commit=False)
				task.user = request.user
				task.project = project
				task.creation_date = timezone.now()
				task.save()
				return HttpResponseRedirect("/%s/" % pk)
		else:
			tasks = Task.objects.filter(project = project).order_by('due_date')
			form = TaskForm()
			context = {
				'form': form,
				'project': project,
				'tasks_list': tasks,
			}
			return render(request, 'project.html', context)
	else:
		return HttpResponseRedirect("/login/")
Esempio n. 9
0
def add_project_task(request, slug):
    if request.user.is_authenticated():
        project = Project.objects.get(slug=slug)
        if request.POST:
            form = TaskForm(request.POST)
            if form.is_valid():
                data = form.cleaned_data
                td = data['end_date'] - data['start_date']
                if td.total_seconds() > 0:
                    task = Task()
                    task.name = data['name']
                    task.description = data['description']
                    task.start_date = data['start_date']
                    task.end_date = data['end_date']
                    task.user = data['user']
                    task.project = project
                    task.save()
                else:
                    messages.add_message(request, messages.ERROR,
                                         " end date is less than start date!")
                    return (redirect(reverse('Task:add_task')))
                return (redirect(reverse('Home:manager')))
            else:
                messages.add_message(request, messages.ERROR, "invalid form")
                return (redirect(reverse('Task:add_task')))
        else:
            form = TaskForm()
            send_dict = {}
            context_instance = RequestContext(request)
            send_dict['project'] = project
            send_dict['form'] = form
            return render_to_response('tasks/add_task.html', send_dict,
                                      context_instance)
    else:
        return redirect(reverse('Login:login'))
Esempio n. 10
0
def task_update(request, pk, template_name='tasks/task_form.html'):
    task = get_object_or_404(Task, pk=pk)
    form = TaskForm(request.POST or None, instance=task)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/')
    return render(request, template_name, {'form': form})
Esempio n. 11
0
    def post(self, request):
        # crear el formulario con los datos del POST
        task_with_user = Task(owner=request.user)
        form = TaskForm(request.POST, instance=task_with_user)

        # validar el formulario
        if form.is_valid():
            # crear la tarea
            task = form.save()

            # mostrar mensaje de exito
            message = 'Tarea creada con éxito! <a href="{0}">Ver tarea</a>'.format(
                reverse('tasks_detail',
                        args=[task.pk
                              ])  # genera la URL de detalle de esta tarea
            )

            # limpiamos el formulario creando uno vacío para pasar a la plantilla
            form = TaskForm()
        else:
            # mostrar mensaje de error
            message = "Se ha producido un error"

        # renderizar la plantilla
        context = {"form": form, "message": message}
        return render(request, 'tasks/new.html', context)
Esempio n. 12
0
def new_list_view(req):
    form = TaskForm(data=req.POST)
    if form.is_valid():
        list = List.objects.create()
        form.save(for_list=list)
        return redirect(list)
    return render(req, 'tasks/home.html', { 'form': form, })
Esempio n. 13
0
def task_edit(request, task_id):
    task_obj = get_object_or_404(Task, pk=task_id)
    accounts = Account.objects.filter(status="open")

    if not (request.user.role == 'ADMIN' or request.user.is_superuser or task_obj.created_by == request.user or request.user in task_obj.assigned_to.all()):
        raise PermissionDenied

    if request.method == 'GET':
        if request.user.role == 'ADMIN' or request.user.is_superuser:
            users = User.objects.filter(is_active=True).order_by('email')
        elif request.user.google.all():
            users = []
        else:
            users = User.objects.filter(role='ADMIN').order_by('email')
        # form = TaskForm(request_user=request.user)
        form = TaskForm(instance=task_obj, request_user=request.user)
        return render(request, 'task_create.html', {'form': form, 'task_obj': task_obj,
                                                    'users': users, 'accounts': accounts, "teams": Teams.objects.all(), })

    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task_obj,
                        request_user=request.user)
        if form.is_valid():
            task = form.save(commit=False)
            task.updated_by = request.user
            previous_assigned_to_users = list(
                task_obj.assigned_to.all().values_list('id', flat=True))
            task.save()
            form.save_m2m()
            # task.assigned_to.clear()
            # task.contacts.clear()
            # task.assigned_to.add(*request.POST.getlist('assigned_to'))
            # task.contacts.add(*request.POST.getlist('contacts'))
            if request.POST.getlist('teams', []):
                user_ids = Teams.objects.filter(id__in=request.POST.getlist(
                    'teams')).values_list('users', flat=True)
                assinged_to_users_ids = task.assigned_to.all().values_list('id', flat=True)
                for user_id in user_ids:
                    if user_id not in assinged_to_users_ids:
                        task.assigned_to.add(user_id)

            if request.POST.getlist('teams', []):
                task.teams.clear()
                task.teams.add(*request.POST.getlist('teams'))
            else:
                task.teams.clear()

            kwargs = {'domain': request.get_host(), 'protocol': request.scheme}
            assigned_to_list = list(
                task.assigned_to.all().values_list('id', flat=True))
            recipients = list(set(assigned_to_list) -
                              set(previous_assigned_to_users))
            send_email.delay(task.id, recipients, **kwargs)
            success_url = reverse('tasks:tasks_list')
            if request.POST.get('from_account'):
                success_url = reverse('accounts:view_account', args=(
                    request.POST.get('from_account'),))
            return JsonResponse({'error': False, 'success_url': success_url})
        else:
            return JsonResponse({'error': True, 'errors': form.errors})
Esempio n. 14
0
def task_update(request, pk, template_name='tasks/task_form.html'):
    task = get_object_or_404(Task, pk=pk)
    form = TaskForm(request.POST or None, instance=task)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/')
    return render(request, template_name, {'form': form})
Esempio n. 15
0
def task_add(request, monitoring_pk, org_pk=None):
    monitoring = get_object_or_404(Monitoring, pk = monitoring_pk)
    if org_pk:
        organization = get_object_or_404(Organization, pk = org_pk)
        redirect = '%s?%s' % (reverse('exmo2010:tasks_by_monitoring_and_organization', args=[monitoring.pk, organization.pk]), request.GET.urlencode())
        title = _('Add new task for %s') % organization.name
    else:
        organization = None
        redirect = '%s?%s' % (reverse('exmo2010:tasks_by_monitoring', args=[monitoring.pk]), request.GET.urlencode())
        title = _('Add new task for %s') % monitoring

    redirect = redirect.replace("%","%%")
    if request.user.has_perm('exmo2010.admin_monitoring', monitoring):
        if request.method == 'GET':
            form = TaskForm(initial={'organization': organization}, monitoring=monitoring)
        elif request.method == 'POST':
            form = TaskForm(request.POST, monitoring=monitoring)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(redirect)

        return TemplateResponse(request, 'exmo2010/task_form.html', {
            'monitoring': monitoring,
            'organization': organization,
            'title': title,
            'form': form
        })
    else:
        return HttpResponseForbidden(_('Forbidden'))
Esempio n. 16
0
def task_add_edit(request, polity_id, task_id=None):
    polity = get_object_or_404(Polity, id=polity_id)
    if not (polity.is_member(request.user)
            or polity.is_wrangler(request.user)):
        raise PermissionDenied()

    if task_id:
        task = get_object_or_404(Task, id=task_id, polity=polity)
        # We don't want to edit anything that has already done.
        if task.is_done:
            raise PermissionDenied()
    else:
        task = Task(polity=polity)

    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            task = form.save()
            return redirect(reverse('task_detail', args=(polity_id, task.id)))
    else:
        form = TaskForm(instance=task)

    ctx = {
        'polity': polity,
        'form': form,
    }
    return render(request, 'tasks/task_add_edit.html', ctx)
Esempio n. 17
0
 def test_createform_task_invalid(self):
     form_data = {
         'name': 'formTest',
         'text': 'testing form',
         'points': '4!'
     }
     form = TaskForm(data=form_data)
     self.assertFalse(form.is_valid())
Esempio n. 18
0
def update_task(request, pk):
    task = Task.objects.get(id=pk)
    form = TaskForm(instance=task)
    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            form.save()
            return redirect('/todo/')
    return render(request, 'tasks/update_task.html', context={'form': form})
Esempio n. 19
0
def index(request):
    tasks = Task.objects.all()
    form = TaskForm(request.POST or None)
    context = {'tasks': tasks, 'form': form}
    if request.method == 'POST':
        if form.is_valid():
            form.save()
        return redirect('index')
    return render(request, 'tasks/list.html', context)
Esempio n. 20
0
def add_task(request):
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            new_task = Task(description=request.POST.get('description', ''))
            new_task.save()
            return HttpResponseRedirect(reverse('task-list'))
    form = TaskForm()
    return render(request, 'tasks/add.html', {'form': form})
Esempio n. 21
0
def task_create(request):
    if request.method == 'GET':
        if request.user.role == 'ADMIN' or request.user.is_superuser:
            users = User.objects.filter(is_active=True).order_by('email')
            accounts = Account.objects.filter(status="open")
        # elif request.user.google.all():
        #     users = []
        #     accounts = Account.objects.filter(created_by=request.user).filter(status="open")
        else:
            users = User.objects.filter(role='ADMIN').order_by('email')
            accounts = Account.objects.filter(
                Q(created_by=request.user)
                | Q(assigned_to__in=[request.user])).filter(status="open")
        form = TaskForm(request_user=request.user)
        return render(
            request, 'task_create.html', {
                'form': form,
                'users': users,
                'accounts': accounts,
                "teams": Teams.objects.all(),
            })

    if request.method == 'POST':
        form = TaskForm(request.POST, request_user=request.user)
        if form.is_valid():
            task = form.save(commit=False)
            task.created_by = request.user
            task.save()
            task.assigned_to.add(*request.POST.getlist('assigned_to'))
            task.contacts.add(*request.POST.getlist('contacts'))

            if request.POST.getlist('teams', []):
                user_ids = Teams.objects.filter(
                    id__in=request.POST.getlist('teams')).values_list(
                        'users', flat=True)
                assinged_to_users_ids = task.assigned_to.all().values_list(
                    'id', flat=True)
                for user_id in user_ids:
                    if user_id not in assinged_to_users_ids:
                        task.assigned_to.add(user_id)

            if request.POST.getlist('teams', []):
                task.teams.add(*request.POST.getlist('teams'))

            kwargs = {'domain': request.get_host(), 'protocol': request.scheme}
            assigned_to_list = list(task.assigned_to.all().values_list(
                'id', flat=True))
            send_email.delay(task.id, assigned_to_list, **kwargs)
            success_url = reverse('tasks:tasks_list')
            if request.POST.get('from_account'):
                success_url = reverse(
                    'accounts:view_account',
                    args=(request.POST.get('from_account'), ))
            return JsonResponse({'error': False, 'success_url': success_url})
        else:
            return JsonResponse({'error': True, 'errors': form.errors})
Esempio n. 22
0
def update(request, pk):
    task = Task.objects.get(pk=pk)
    form = TaskForm(instance=task)
    context = {'task': task, 'form': form}
    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            form.save()
        return redirect('index')
    return render(request, 'tasks/update.html', context)
Esempio n. 23
0
def updateTask(request, pk):
    item = Task.objects.get(id=pk)
    form_update = TaskForm(instance=item)
    if request.method == 'POST':
        form_update = TaskForm(request.POST, instance = item)
        if form_update.is_valid():
            form_update.save()
            return redirect('/')
    context = {'form_update':form_update}
    return render(request, 'tasks/update_task.html',context)
Esempio n. 24
0
def create_task(request):
    if request.method == "POST":
        form = TaskForm(request.POST)
        if form.is_valid():
            new_task = form.save(commit=False)
            new_task.last_success = "N/A"
            new_task.last_failure = "N/A"
            new_task.last_duration = "N/A"
            new_task.operator = "N/A"
            new_task.status = "N/A"
            new_task.created_by = request.user
            new_task.updated_by = request.user
            if form.is_valid():  # All validation rules pass
                new_task.save()
                return HttpResponseRedirect("/tasks/")  # Redirect after POST
    else:
        form = TaskForm()  # An unbound form

    return render(request, "tasks/create_task_form.html", {"form": form})
Esempio n. 25
0
def index(request):
    consulta = Task.objects.all()
    form = TaskForm()
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
        return redirect('/')      
    context = {'info':consulta,'temp':form}
    return render(request,"tasks/list.html", context)
Esempio n. 26
0
def index_view(request, *args, **kwargs):
    tasks = Task.objects.all()
    form = TaskForm(request.POST)

    if form.is_valid():
        form.save()
        return redirect('/')

    context = {'tasks': tasks, 'form': form}
    return render(request, 'tasks/index.html', context)
Esempio n. 27
0
def task_create(request, template_name='tasks/task_form.html'):
    form = TaskForm(request.POST or None)

    if form.is_valid():
        task = form.save(commit=False)
        task.user = request.user
        task.save()
        return redirect('tasks:task_list')

    return render(request, template_name, {'form': form})
Esempio n. 28
0
def task_create(request, template_name='tasks/task_form.html'):
    form = TaskForm(request.POST or None)
    if form.is_valid():
        task, dummy = Task.objects.get_or_create(
            title=form.cleaned_data['title'],
            priority=form.cleaned_data['priority'],
            user=request.user)
        task.save()
        return HttpResponseRedirect('/')
    return render(request, template_name, {'form': form})
Esempio n. 29
0
def task_add(request, monitoring_id, organization_id=None):
    monitoring = get_object_or_404(Monitoring, pk = monitoring_id)
    if organization_id:
        organization = get_object_or_404(Organization, pk = organization_id)
        redirect = '%s?%s' % (reverse('exmo2010:tasks_by_monitoring_and_organization', args=[monitoring.pk, organization.pk]), request.GET.urlencode())
        title = _('Add new task for %s') % organization.name
    else:
        organization = None
        redirect = '%s?%s' % (reverse('exmo2010:tasks_by_monitoring', args=[monitoring.pk]), request.GET.urlencode())
        title = _('Add new task for %s') % monitoring

    redirect = redirect.replace("%","%%")
    current_title = _('Add task')
    if request.user.has_perm('exmo2010.admin_monitoring', monitoring):
        if request.method == 'GET':
            form = TaskForm(initial={'organization': organization}, monitoring=monitoring)

            crumbs = ['Home', 'Monitoring', 'Organization']
            breadcrumbs(request, crumbs, monitoring)

            return render_to_response(
                'exmo2010/task_form.html',
                {
                    'monitoring': monitoring,
                    'organization': organization,
                    'current_title': current_title,
                    'title': title,
                    'form': form
                },
                context_instance=RequestContext(request),
            )
        if request.method == 'POST':
            form = TaskForm(request.POST, monitoring=monitoring)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(redirect)
            else:

                crumbs = ['Home', 'Monitoring', 'Organization']
                breadcrumbs(request, crumbs, monitoring)

                return render_to_response(
                    'exmo2010/task_form.html',
                    {
                        'monitoring': monitoring,
                        'organization': organization,
                        'current_title': current_title,
                        'title': title,
                        'form': form
                    },
                    context_instance=RequestContext(request),
                )
    else:
        return HttpResponseForbidden(_('Forbidden'))
Esempio n. 30
0
 def test_task_form(self):
     user = User.objects.get(id=1)
     status = TaskStatus.objects.get(id=1)
     form_data = {
         "name": "test name",
         "description": "test descrition",
         "status": status,
         "assigned_to": user,
     }
     form = TaskForm(data=form_data)
     self.assertTrue(form.is_valid())
Esempio n. 31
0
def task_create(request, template_name='tasks/task_form.html'):
    form = TaskForm(request.POST or None)
    if form.is_valid():
        task, dummy = Task.objects.get_or_create(
            title=form.cleaned_data['title'],
            priority=form.cleaned_data['priority'],
            user=request.user
        )
        task.save()
        return HttpResponseRedirect('/')
    return render(request, template_name, {'form': form})
Esempio n. 32
0
def task_create(request, template_name="tasks/task_form.html"):
    form = TaskForm(request.POST or None)

    if form.is_valid():
        task = form.save(commit=False)
        task.user = request.user
        task.save()
        form.save_m2m()
        return redirect("tasks:task_list")

    return render(request, template_name, {"form": form})
Esempio n. 33
0
 def post(self, request, task_id):
     task = get_object_or_404(Task, id=task_id)
     form = TaskForm(request.POST)
     if form.is_valid():
         task.title = form.cleaned_data['title']
         task.description = form.cleaned_data['description']
         task.deadline = form.cleaned_data['deadline']
         task.priority = form.cleaned_data['priority']
         task.save()
         return HttpResponseRedirect(reverse('task_list'))
     context = {'task': task, 'form': form}
     return render(request, 'tasks/task_edit.html', context=context)
Esempio n. 34
0
def task_update(request, pk, template_name='tasks/task_form.html'):
    if request.user.is_superuser:
        task = get_object_or_404(Task, pk=pk)
    else:
        task = get_object_or_404(Task, pk=pk)
    form = TaskForm(request.POST or None, instance=task)

    if form.is_valid():
        form.save()
        return redirect('tasks:task_list')

    return render(request, template_name, {'form': form})
Esempio n. 35
0
def index(request):
    tasks = Task.objects.all()

    form = TaskForm()

    if (request.method == 'POST'):
        form = TaskForm(request.POST)
        if (form.is_valid()):
            form.save()
        return redirect('/')

    context = {'tasks': tasks, 'form': form}
    return render(request, 'tasks/list.html', context)
Esempio n. 36
0
def update_task(request, pk):
    """Updates specific task requested to be updated (recieving pk/id of the task) that belongs to the loggedin user by the loggedin user"""
    task = Task.objects.get(id=pk) # getting the requested task as object by id from db.
    task_update_form = TaskForm(instance=task) # displaying a form for updating with displaying an instance of the last saved date of the task.
    if request.method == "POST": # if request method is POST (which is sent by html form):
        task_update_form = TaskForm(request.POST, instance=task) # pass the request POST data to the form and any instance of task data that hasn't got changed
        if task_update_form.is_valid(): # if form is valid:
            task_update_form.save(commit=True) # save changes recieved from the form to the database.
            return redirect("index") # redirect to home page
        else: # if form is not valid
            messages.info(request, "Invalid data requirements") # create a message to display to the user
            return redirect("update_task", pk=pk) # refresh the page of task update of its specific id/pk.
    return render(request, "tasks/task_update.html", {"form": task_update_form}) # return rendering the request, the template, and the form as context dictionary.
Esempio n. 37
0
def task_edit(request, task_id):
    task_obj = get_object_or_404(Task, pk=task_id)

    if not (request.user.role == 'ADMIN' or request.user.is_superuser
            or task_obj.created_by == request.user):
        raise PermissionDenied

    if request.method == 'GET':
        if request.user.role == 'ADMIN' or request.user.is_superuser:
            users = User.objects.filter(is_active=True).order_by('email')
        elif request.user.google.all():
            users = []
        else:
            users = User.objects.filter(role='ADMIN').order_by('email')
        # form = TaskForm(request_user=request.user)
        form = TaskForm(instance=task_obj, request_user=request.user)
        return render(request, 'task_create.html', {
            'form': form,
            'task_obj': task_obj,
            'users': users
        })

    if request.method == 'POST':
        form = TaskForm(request.POST,
                        instance=task_obj,
                        request_user=request.user)
        if form.is_valid():
            task = form.save(commit=False)
            form.save_m2m()
            # task.assigned_to.clear()
            # task.contacts.clear()
            # task.assigned_to.add(*request.POST.getlist('assigned_to'))
            # task.contacts.add(*request.POST.getlist('contacts'))
            if request.POST.getlist('teams', []):
                user_ids = Teams.objects.filter(
                    id__in=request.POST.getlist('teams')).values_list(
                        'users', flat=True)
                assinged_to_users_ids = task.assigned_to.all().values_list(
                    'id', flat=True)
                for user_id in user_ids:
                    if user_id not in assinged_to_users_ids:
                        task.assigned_to.add(user_id)
            kwargs = {'domain': request.get_host(), 'protocol': request.scheme}
            send_email.delay(task.id, **kwargs)
            return JsonResponse({
                'error': False,
                'success_url': reverse('tasks:tasks_list')
            })
        else:
            return JsonResponse({'error': True, 'errors': form.errors})
Esempio n. 38
0
def edit_task(request, task_id):
    task = get_object_or_404(Task, pk=task_id)
    old_value = task.created_by
    name = task.name
    if request.method == "POST":
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():  # All validation rules pass
            current_task = form.save(commit=False)
            current_task.name = name
            current_task.last_success = "N/A"
            current_task.last_failure = "N/A"
            current_task.last_duration = "N/A"
            current_task.operator = "N/A"
            current_task.status = "N/A"
            current_task.created_by = old_value
            current_task.updated_by = request.user
            if form.is_valid():
                current_task.save()
                return HttpResponseRedirect("/tasks/")  # Redirect after POST
    else:
        form = TaskForm(instance=task)  # An bound form

    return render(request, "tasks/edit_task_form.html", {"form": form, "task": task})
Esempio n. 39
0
def index(request):
    tasks = Task.objects.all()
    form = TaskForm()

    if request.method == "POST":
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
        else:
            print('error')
        return redirect('/')

    context = {'tasks': tasks, 'form': form}
    return render(request, 'tasks/index.html', context)
Esempio n. 40
0
def create_task(request, column_id, board_id):
    if request.method == "POST":
        column = Column.objects.get(id=column_id)
        form = TaskForm(request.POST)
        if form.is_valid():
            task = form.save(commit=False)
            task.column = column
            task.author = request.user
            task.pub_date = timezone.now()
            task.save()
            column.task.add(task)
        return redirect('/boards/{}'.format(board_id))
    else:
        form = TaskForm()
    return render(request, "tasks/create_task.html", {'form': form})
Esempio n. 41
0
def create(request):
	if request.user.is_authenticated():
		if request.method == "POST":
			form = TaskForm(request.POST)
			if form.is_valid():
				task = form.save(commit=False)
				task.user = request.user
				task.creation_date = timezone.now()
				task.save()
				return HttpResponseRedirect("/tasks/")
		else:
			form = TaskForm()
		return render(request, 'tasks/create.html', {'form': form})
	else:
		return HttpResponseRedirect("/login/")
Esempio n. 42
0
def create_task(request):
    """Allowing user to create new task."""
    task_create_form = TaskForm() # displaying task creation form for the user and taking it to a handler.
    if request.method == "POST":
        task_create_form = TaskForm(request.POST) # pass the request POST data to the django form.
        if task_create_form.is_valid(): # if form is valid:
            new_task = task_create_form.save(commit=False) # giving new_task handler the responsibility of what to do after validation, without commiting data the user entered to the db.
            new_task.user = request.user # setting the user of task to the loggedin user who sent the request.
            new_task.save() # commiting and saving the task to the db.
            return redirect("index") # redirect to the home page.
        else: # if form is not valid:
            messages.info(request, "Invalid data requirements.") # create a message for the user that displays after refreshing the page.
            return redirect("create_task") # redirecting the page to itself (refreshing)
    else: # if request is not POST
        return render(request, "tasks/task_create.html", {"form": task_create_form})
Esempio n. 43
0
def task_create(request):
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            task = form.save(commit=False)
            task.author = request.user
            task.save()

            return HttpResponseRedirect(reverse('tasks_traditional:task_list'))
        else:
            ctx = {'form': form}
    else:
        ctx = {'form': TaskForm()}

    return render(request, 'tasks/task_form.html', ctx)
Esempio n. 44
0
def create_task(form_data, method='create', instance=None):
    taskform = TaskForm(form_data)
    if taskform.is_valid():
        name = taskform.cleaned_data['name']
        description = taskform.cleaned_data['description']
        status = taskform.cleaned_data['completion_status']
        start_date = form_data['start_date']
        if start_date == '':
            start_date = None
        end_date = form_data['end_date']
        if end_date == '':
            end_date = None
        if start_date > end_date:
            start_date = None
            end_date = None
        try:
            tasklist_id = form_data['tasklist_id']
            mytaklist = TaskList.objects.get(id=tasklist_id)
        except:
            mytaklist = None
        parentid = None
        if method == 'subtask':
            parentid = form_data['parentid']

        if method == 'create' or method == 'subtask':
            if start_date is None or end_date is None:
                task = TasksModel(name=name, description=description, completion_status=status,
                                  tasklist_id=mytaklist, parent_id=parentid, root_id=parentid)
                task.save()
            else:
                task = TasksModel(name=name, description=description, completion_status=status,
                                  tasklist_id=mytaklist, start_date=start_date, end_date=end_date, parent_id=parentid,
                                  root_id=parentid)
                task.save()

        elif method == 'edit':
            task = TasksModel.objects.get(id=instance.id)
            task.name = name
            task.description = description
            task.completion_status = status
            if start_date is not None and end_date is not None:
                task.start_date = start_date
                task.end_date = end_date
            if mytaklist is not None:
                task.tasklist_id = mytaklist
            task.save()
        return 0
    return 255
Esempio n. 45
0
def edit(request, task_id):
    try:
        p = Task.objects.get(pk=task_id)
    except Task.DoesNotExist:
        raise Http404

    if request.method == 'POST':
        f = TaskForm(request.POST, instance=p)
        if f.is_valid():
            task = f.save(commit=False)
            task.updated_by = request.user
            task.save()
            return HttpResponseRedirect(reverse('task-index'))
    else:
        f = TaskForm(instance=p)

    return render_to_response('tasks/edit.html', { 'form' : f, 'task' : p },
        context_instance=RequestContext(request))
Esempio n. 46
0
File: views.py Progetto: rif/todo
def task_edit(request, task_id=None):
    "used for both creation and editing of a task"
    task = None
    if task_id:
        task = get_object_or_None(Task, pk=task_id)
    if task and task.user != request.user:
        raise PermissionDenied()
    if request.method == 'POST': 
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            task = form.save(commit=False)
            task.user = request.user
            task.save()
            return redirect('tasks:index')
    else:
        form = TaskForm(instance=task) 

    return locals()
Esempio n. 47
0
def new(request):
    if request.method == 'POST':
        f = TaskForm(request.POST)
        if f.is_valid():
            task = f.save(commit=False)
            task.created_by = request.user
            task.updated_by = request.user
            task.save()

            if 'project' in request.POST:
                return HttpResponseRedirect(reverse('project-detail',
                    args=request.POST['project']))
            else:
                return HttpResponseRedirect(reverse('task-index'))

    else:
        f = TaskForm()

    return render_to_response('tasks/new.html', { 'form': f },
        context_instance=RequestContext(request))
Esempio n. 48
0
def newtask(request):
	if request.method == 'GET':
		form = TaskForm()
		return render_to_response('tasks/newtask.html',
			RequestContext(request, {'form': form,}))
	else:
		form = TaskForm(request.POST)
		if form.is_valid():
			ttp = request.POST.get('task_type', 0)
			arg = request.POST.get('param', '')
			if ttp == 0:
				return render_to_response('tasks/newtask.html', \
				RequestContext(request, {'form': form,}))
			else:
				task = Task()
				task.task_type = ttp
				task.user = request.user
				task.param = arg
				task.pub_date = timezone.now()
				task.save()
				return HttpResponseRedirect("/tasks/")
		else:
			return render_to_response('tasks/newtask.html', 
				RequestContext(request,{'form':form}))