Exemplo n.º 1
0
def project_edit(request, pk):
    if request.user.account.demo:
        raise Http404

    project = get_object_or_404(Project, pk=pk)
    project_manager = project.project_manager

    if project.archived:
        raise Http404
    elif not (request.user.account.role == 'admin'
              or request.user.account.role == 'project_manager'):
        raise Http404
    elif request.user.account.role == 'project_manager' and request.user.account != project_manager:
        raise Http404

    if request.method == 'POST':
        form = ProjectForm(request.POST, instance=project)
        if form.is_valid():
            new_project_manager = form.save().project_manager
            if not project_manager == new_project_manager:
                Notification.objects.create(
                    title=f'Project Edited',
                    text=
                    f'You have been removed as project manager from "{project.title}"',
                    recipient=project_manager)
                Notification.objects.create(
                    title=f'Project Edited',
                    text=
                    f'You have been appointed as project manager for "{project.title}"',
                    recipient=new_project_manager)

            return redirect('project_detail_ticket_open', pk)

    return render(request, 'projects/project_edit.html',
                  {'form': ProjectForm(instance=project)})
Exemplo n.º 2
0
def edit_project(request,projectid):
    names= ['Material Purchase','Make Payment','Invoices','Payments']
    links = ['/projects/'+projectid+'/purchases','/projects/'+projectid+'/payments','/projects/'+projectid+'/invoices','/projects/'+projectid+'/allpayments']
    submenus = create_sub(names,links)
    proj = get_object_or_404(Project, pk=projectid)
    context = {'proj_selected':'current'}
    
    if len(request.POST) <= 0:
        data = {'name':proj.name,'location':proj.location,'city':proj.city,'owner':proj.owner,'start_date':proj.start_date,'end_date':proj.end_date}
        form = ProjectForm(data)
        context.update({'title':'Update Project Details','form':form,'submenus':submenus})
        return render(request, "edit.html", context)
    else:
        form = ProjectForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            proj.name = cd.get('name')
            proj.location = cd.get('location')
            proj.city = cd.get('city')
            proj.owner = cd.get('owner')
            proj.start_date = cd.get('start_date')
            proj.end_date = cd.get('end_date')
            proj.save();
            url = reverse('projects')
            return HttpResponseRedirect("%s?success=1"%(url))
        else:
            context.update({'title':'Update Project Details','form':form,'submenus':submenus})
            return render(request, "edit.html",context)
Exemplo n.º 3
0
def submit_project(request):
    form = ProjectForm(request.POST or None)
    if form.is_valid():
        project = form.save(commit=False)
        project.user = request.user
        project.save()

        subject = "Project Submission Notice"
        message = "This is to inform you that your project '" + project.name + "' has been submitted for vetting."
        project_owner = request.user.email


        to_owner_email = EmailMessage(subject, message, [project_owner])
        to_owner_email.send()

        subject = "Project Submission Notice"
        message = "This is to inform you that " + request.user.userprofile.first_name + " " + request.userprofile.last_name " has submitted a project named " + project.name + " with you listed as an adviser."
        project_adviser = project.adviser_email
    

        to_adviser_email = EmailMessage(subject, message, [project_adviser])
        to_adviser_email.send()

        return redirect(project)
    return render_to_response('add_project.html',
                              {'form': form},
                              context_instance=RequestContext(request))
Exemplo n.º 4
0
def add_project_view(request):
    if request.user.is_authenticated() and request.user.is_staff:
        if request.POST:
            form = ProjectForm(request.POST)
            if form.is_valid():
                data = form.cleaned_data
                td = data['end_date'] - data['start_date']
                if td.total_seconds()>0:
                    project = Project()
                    project.name = data['name']
                    project.description = data['description']
                    project.start_date = data['start_date']
                    project.end_date = data['end_date']
                    project.user = User.objects.get(username = request.user.username)
                    project.save()
                else:
                    messages.add_message(request, messages.ERROR,
                        " end date is less than start date!")
                    return (redirect(reverse('Home:add_project')))
                return (redirect(reverse('Home:manager')))
            else:
                messages.add_message(request, messages.ERROR, 
                    "invalid form")
                return (redirect(reverse('Home:add_project')))
        else:
            form = ProjectForm()
            send_dict={}
            send_dict['form'] = form
            return render_to_response('managers/add_project.html',send_dict,context_instance=RequestContext(request))
    else:
        return redirect(reverse('Login:login'))
Exemplo n.º 5
0
    def post(self, request):
        var = ''
        form = ProjectForm(request.POST, request.FILES)
        form2 = ProfileForm(request.POST, request.FILES)
        projects = request.user.projects.all()
        template_name = 'capturista/home.html'
        if form.is_valid():
            pro = form.save(commit=False)
            pro.user = request.user
            pro.save()
            messages.success(request, "Proyecto guardado con éxito")
            context = {'section': 'alta', 'num_projects': projects.count()}

        else:
            context = {
                'section': 'alta',
                'form': form,
                'form2': form2,
                'num_projects': projects.count()
            }
            return render(request, template_name, context)

        if form2.is_valid():
            perf = form2.save(commit=False)
            perf.uid = pro.uid
            perf.save()
            return redirect('projects:detail', id=pro.id)
Exemplo n.º 6
0
def projectsubmit(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            pd = form.save(commit=False)
            pd.sub_date = timezone.now()
            pd.approved = False

            # format the authors list
            al = pd.authors.strip().replace('\r\n', '*').replace('\r', '*').replace('\n', '*').split('*')
            print al
            if len(al) > 1:
                al[-1] = 'and ' + al[-1].strip()

            if len(al) > 2:
                pd.authors = ', '.join(al)
            else:
                pd.authors = ' '.join(al)

            # make the thumbnail url a direct link if not already
            if pd.thumbnail_url:
                thumb = pd.thumbnail_url.strip()
                if 'imgur' in thumb and 'i.' not in thumb:
                    pd.thumbnail_url = 'i.' + thumb.replace('https://', '').replace('http://', '')
                if '.jpg' not in pd.thumbnail_url:
                    pd.thumbnail_url += '.jpg'

            pd.save()
            return render(request, 'projects/projectsubmit.html', {'submitted': True})
    else:
        form = ProjectForm()
    return render(request, 'projects/projectsubmit.html', {'form': form, 'submitted': False})
Exemplo n.º 7
0
def create(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)

        if form.is_valid():
            project = form.save(commit=False)

            # On vérifie que le slug n'existe pas en bdd
            i = 0
            found = False
            while not found:
                if i > 0:
                    slug = slugify(form.cleaned_data['title']) + '-' + str(i)
                else:
                    slug = slugify(form.cleaned_data['title'])
                if Project.objects.filter(slug__iexact=slug).count() == 0:
                    project.slug = slug
                    found = True
                i += 1

            project.save()
            project.author.add(request.user.id)
            return redirect('projects_view', slug=slug)
    else:
            form = ProjectForm()

    return render(request, 'projects/edit.html', {'form': form})
Exemplo n.º 8
0
Arquivo: views.py Projeto: USEPA/TRACI
 def post(self, request, *args, **kwargs):
     """Process the post request with a new Project form filled out."""
     form = ProjectForm(request.POST)
     if form.is_valid():
         form.save(commit=True)
         return HttpResponseRedirect('/projects/projects/')
     return render(request, "project_create.html", {'form': form})
Exemplo n.º 9
0
def getrepos():
    """
    This function collects all the repos from
    GitHub and store them in the database
    """
    projects = requests.get('https://api.github.com/orgs/kodkollektivet/repos' + OAUTH_TOKEN).json()

    for project in projects:

        readme = requests.get(
            'https://api.github.com/repos/kodkollektivet/' + project['name'] + '/readme' + OAUTH_TOKEN).json()

        try:
            readme = b64decode(readme['content'])
        except:
            readme = ''

        form = ProjectForm({
            'gh_name': project['name'],
            'gh_id': project['id'],
            'gh_url': project['html_url'],
            'gh_readme': readme
        })

        if form.is_valid():
            # Creates or updates a project. It fist looks it match on gh_name
            pro, created = Project.objects.update_or_create(gh_name=form.data['gh_name'], defaults=form.data)

            languages = requests.get('https://api.github.com/repos/kodkollektivet/'+project['name']+'/languages' + OAUTH_TOKEN).json()

            for key, value in languages.iteritems():
                lan, created = Language.objects.update_or_create(name=key)
                obj, created = ProLan.objects.update_or_create(project=pro, language=lan)
Exemplo n.º 10
0
def __project_edit(project, request):
	usr = request.user
	# print(request.POST)
	tasksToRemove = request.POST["tasksToRemove"]
	peopleToRemove = request.POST["peopleToRemove"]
	filesToRemove = request.POST["filesToRemove"]
	peopleToAdd = request.POST["peopleToAdd"]

	form = ProjectForm(request.POST)
	if form.is_valid():
		project.name = form.cleaned_data['name']
		project.complete = form.cleaned_data['complete']
		project.description = form.cleaned_data['description']
		project.createdBy =request.user
		project.save(False,True)
		# remove composites
		try:
			# TODO
			tasksToRemove = json.loads(tasksToRemove)
			peopleToRemove = json.loads(peopleToRemove)
			peopleToAdd = json.loads(peopleToAdd)
			with transaction.atomic():
				Task.objects.filter(projectId=project).filter(id__in=tasksToRemove).delete()
				PersonInProject.objects.filter(projectId=project).filter(userId__in=peopleToRemove).delete()
				# 	File.objects.filter(projectId=project).filter(id__in=filesToRemove).delete()
				for userId in peopleToAdd:
					print(">>"+str(userId))
					u = User.objects.get(id=userId)
					if u:
						PersonInProject(projectId=project, userId=u, createdBy=usr).save()
		except (User.DoesNotExist,Exception) as e:
			print("Error modifying project's companion objects: "+ str(e))
		return True, {}
	else:
		return False, list(form.errors.keys()) if form.errors else None
Exemplo n.º 11
0
def edit_project(request, id):
    project = Project.objects.get(pk=id)
    architects = Architect.objects.values('architect__username', 'id')
    owners = Owner.objects.values('first_name', 'last_name', 'id')

    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            project.architect = data['architect']
            project.owner = data['owner']
            project.name = data['name']
            project.area = data['area']
            project.type = data['type']
            project.start_date = data['start_date']
            project.end_date = data['end_date']
            project.save()
            return redirect('list_projects')
    else:
        form = ProjectForm()

    return render(
        request, 'projects/edit_project.html', {
            'project': project,
            'form': form,
            'architects': architects,
            'owners': owners,
            'types': Project.BUILDING_TYPES
        })
Exemplo n.º 12
0
def add_project_view(request):
    if request.user.is_authenticated() and request.user.is_staff:
        if request.POST:
            form = ProjectForm(request.POST)
            if form.is_valid():
                data = form.cleaned_data
                td = data['end_date'] - data['start_date']
                if td.total_seconds() > 0:
                    project = Project()
                    project.name = data['name']
                    project.description = data['description']
                    project.start_date = data['start_date']
                    project.end_date = data['end_date']
                    project.user = User.objects.get(
                        username=request.user.username)
                    project.save()
                else:
                    messages.add_message(request, messages.ERROR,
                                         " end date is less than start date!")
                    return (redirect(reverse('Home:add_project')))
                return (redirect(reverse('Home:manager')))
            else:
                messages.add_message(request, messages.ERROR, "invalid form")
                return (redirect(reverse('Home:add_project')))
        else:
            form = ProjectForm()
            send_dict = {}
            send_dict['form'] = form
            return render_to_response('managers/add_project.html',
                                      send_dict,
                                      context_instance=RequestContext(request))
    else:
        return redirect(reverse('Login:login'))
Exemplo n.º 13
0
def edit_project(request, project_id):
    # if freelancer is not working on the project return forbidden
    if Freelancer.objects.filter(email=request.user.email).exists() and \
            Freelancer.objects.get(email=request.user.email).current_project != project_id:
        return HttpResponseForbidden()

    # if user is not owner of the project return forbidden
    elif not Freelancer.objects.filter(email=request.user.email).exists() and \
            Appointment.objects.get(email=request.user.email).project_number != project_id:
        return HttpResponseForbidden()

    project_i = get_object_or_404(Project, project_number=project_id)
    if request.method == 'POST':

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

        if form.is_valid():
            form = form.save()
            messages.success(request, f'Details updated successfully!{form} ')
            return redirect(reverse('freelancer'))

        else:
            messages.error(
                request, 'There is something wrong with your form '
                ' Please check your input! ')

            return render(request, 'freelancers/dashboard.html',
                          {'form': form})
Exemplo n.º 14
0
class ProjectFormTest(SimpleTestCase):
    """ """
    def setUp(self):
        self.form = ProjectForm()

    def test_init(self):
        self.assertEqual(self.form.fields['repo'].widget.attrs['placeholder'],
                         'ex: https://github.com/srtab/alexandriadocs')
        self.assertEqual(self.form.fields['tags'].widget.attrs['placeholder'],
                         'ex: django, python')

    def test_form_helper(self):
        self.assertIsNotNone(self.form.helper.layout)

    @patch('projects.forms.group_access_checker.has_access',
           return_value=False)
    def test_clean_group_without_access(self, mhas_access):
        setattr(self.form, 'cleaned_data', {})
        with self.assertRaises(ValidationError):
            self.form.clean_group()
            mhas_access.assert_called_with(None, None, AccessLevel.ADMIN)

    @patch('projects.forms.group_access_checker.has_access', return_value=True)
    def test_clean_group_with_access(self, mhas_access):
        setattr(self.form, 'cleaned_data', {'group': 'group'})
        self.assertEqual(self.form.clean_group(), 'group')
Exemplo n.º 15
0
def edit_project(request, project_id):
    project = Project.objects.get(pk=project_id)
    if request.method == 'POST':
        form = ProjectForm(request.POST, instance=project)
        if form.is_valid():
            print(">>>>>>>>>>>>>>>>>>", form.cleaned_data)
            project = form.save(commit=False)
            project.save()
            members_queryset = form.cleaned_data.get("members")
            # ProjectMembers.objects.filter(project=project).delete()
            print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", members_queryset.all().values_list('id', flat=True))
            print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", Membership.objects.filter(project=project))
            for id in Membership.objects.select_related().filter(project=project).values_list('user__id', flat=True):
                if id not in members_queryset.all().values_list('id', flat=True):
                    Membership.objects.filter(project=project, user__id=id).delete()

            for member in members_queryset.all():

                if not Membership.objects.filter(project=project, user=member).exists():
                    Membership.objects.create(user=member, project=project)

            return render(request, 'projects/includes/_project-card.html', {
                'project': project,
            })
        else:
            data = form.errors.as_json()
            return JsonResponse(data, safe=False, status=400)
Exemplo n.º 16
0
def project_create(request):
	usr = request.user
	if request.method == "POST" and request.is_ajax():
		print(request.POST)
		form = ProjectForm(request.POST)
		if form.is_valid():
			p = Project(name=form.cleaned_data['name'],
						complete=form.cleaned_data['complete'],
						description=form.cleaned_data['description'],
						createdBy=usr)
			p.save(True,False)
			# add creator as admin !
			pip = PersonInProject(projectId=p,
					  	userId=usr,
						role=PersonInProject.PERSON_ROLE[1][0],
						createdBy=usr)
			pip.save(True,False)
			return HttpResponse(json.dumps({"status":"OK","id":p.id}))
		else:
			errors_fields = dict()
			if form.errors:
				errors_fields["fields"] = list(form.errors.keys())
			return HttpResponseBadRequest(json.dumps(errors_fields), content_type="application/json")
	else:
		template = loader.get_template('project_write.html')
		context = RequestContext(request, get_context({
			'new_project': True,
			'data_page_type': 'projects'
		}, request))
		return HttpResponse(template.render(context))
Exemplo n.º 17
0
    def post(self, request):
        context_dict = {}

        form = ProjectForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/api/projects?registerSuccess=true')
        return self.get(request)
Exemplo n.º 18
0
    def post(self, request, *args, **kwargs):
        try:
            # Explicitly setting the request.post to be mutable so that we can add additional values to it.
            #once done, reset the mutable property. dont need to do this if a form is a multi-part form.
            mutable = request.POST._mutable
            request.POST._mutable = True
            #Set added by updated by user on form post data
            self.set_added_by_update_by_users_on_view(request, GlobalConstants.ADD_ACTION)
            request.POST._mutable = mutable
            projectform = ProjectForm(request.POST)

            project_members_response = {}
            project_members_list = [project_member for project_member in request.POST.getlist('project_members') if
                                    project_member != ""]
            project_members_values_list = [int(project_member_value) for project_member_value in
                                           request.POST.getlist('project_members_value') if project_member_value != ""]

            if projectform.is_valid():
                #First check if the project resources has no freely typed internal user name
                if len(project_members_list) != len(project_members_values_list):
                    if project_members_values_list:
                        actual_project_members = InternalResource.objects.filter(id__in=project_members_values_list)
                        for member in project_members_list:
                            if member not in actual_project_members:
                                project_members_response[str(project_members_list[member])] = str(
                                    project_members_list[member] + " is not a valid Internal Resource")
                                # else:
                                #     project_members_response[member]
                    else:
                        project_members_response[str(project_members_list[0])] = str(
                            project_members_list[0] + " is not a valid Internal Resource")
                    context = self.get_context_data()
                    context['project_members_response'] = project_members_response
                    context['form'] = projectform
                    return self.render_to_response(context)
                else:
                    self.object = projectform.save()
                    super(AddProject, self).form_valid(projectform)
                    for member in project_members_values_list:
                        member = InternalResource.objects.get(id=int(member))
                        project_resource = ProjectResources(project_id=self.object, resource_id=member,
                                                            addedBy=request.user,
                                                            updatedBy=request.user,
                                                            is_active=True)
                        project_resource.save()
                    return HttpResponseRedirect(self.get_success_url())
            else:
                actual_project_members = InternalResource.objects.filter(id__in=project_members_values_list)
                for member in project_members_list:
                    if member not in actual_project_members:
                        project_members_response[member] = ["0", member + "-"]
                    else:
                        project_members_response[member] = [actual_project_members[member].id, ""]

                return self.form_invalid(form=projectform, project_members_response=project_members_response)

        except Exception as e:
            logger.error("Exception while adding Project: " + str(e))
Exemplo n.º 19
0
def project_add(request):
    form = ProjectForm(request.POST or None)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse("projects-list"))
    return direct_to_template(request, "project_add.html", extra_context={
        "form": form,
        "nav": {"selected": "projects",},
    })
Exemplo n.º 20
0
def project_edit(request, pk):
    form = ProjectForm(request.POST or None, instance=Project.get(pk))
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse("projects-list"))
    return direct_to_template(request, "project_edit.html", extra_context={
        "form": form,
        "nav": {"selected": "projects",},
    })
Exemplo n.º 21
0
def edit_project(request, p_id):
    authors = Author.objects.all()
    teachers = Teacher.objects.all()
    fields = Field.objects.all()
    langs = Project.langChoices
    project_types = Project.formChoices
    courses = Project.courseChoices
    users = User.objects.filter(profile__is_approved=True)
    p = Project.objects.get(pk=p_id)
    if request.method == 'POST':
        pr = ProjectForm(request.POST, request.FILES)
        if pr.is_valid():
            file_form = DictFileForm(request.POST, request.FILES)
            if file_form.is_valid():
                p.file.file = request.FILES['file']
            p.author.clear()
            p.author.add(*request.POST.getlist('author'))
            p.field.clear()
            p.field.add(*request.POST.getlist('field'))
            p.prof.clear()
            p.prof.add(*request.POST.getlist('prof'))
            p.title = request.POST['title']
            p.title_en = request.POST['title_en']
            p.keywords = request.POST['keywords']
            p.keywords_en = request.POST['keywords_en']
            p.abstract = request.POST['abstract']
            p.abstract_en = request.POST['abstract_en']
            p.link = request.POST['link']
            p.course = request.POST['course']
            p.form = request.POST['form']
            p.lang = request.POST['lang']
            p.user = User.objects.get(pk=int(request.POST['user']))
            if request.POST['mark']:
                p.mark = request.POST['mark']
            p.save()
            show_form = False
            valid = True
            return render(request, 'profile/edit.html', locals())
        else:
            errors = pr.errors
            show_form = True
            valid = False
            field_set = set(p.field.values_list('id', flat=True))
            prof_set = set(p.prof.values_list('id', flat=True))
            author_set = set(p.author.values_list('id', flat=True))
            render(request, 'profile/edit.html', locals())
    else:
        p = Project.objects.get(pk=p_id)
        project_form = ProjectForm()
        file_form = DictFileForm()
        show_form = True
        valid = True
        field_set = set(p.field.values_list('id', flat=True))
        prof_set = set(p.prof.values_list('id', flat=True))
        author_set = set(p.author.values_list('id', flat=True))
    return render(request, 'profile/edit.html', locals())
Exemplo n.º 22
0
def submit_project(request):
    form = ProjectForm(request.POST or None)
    if form.is_valid():
        project = form.save(commit=False)
        project.user = request.user
        project.save()
        return redirect(project)
    return render_to_response('add_project.html',
                              {'form': form},
                              context_instance=RequestContext(request))
Exemplo n.º 23
0
	def post(self, request):
		form = ProjectForm(request.POST)

		if form.is_valid():
			project = form.save()
			messages.success(request, 'Project \'' + project.name + '\' was successfully created.')
			return redirect('/projects')
		else:
			messages.error(request, 'Sorry, but there was a problem with the information you supplied.')
			return render_create(request, form)
Exemplo n.º 24
0
def project_edit(request, pk):
    form = ProjectForm(request.POST or None,
                       instance=Project.objects.get(pk=pk))
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse("projects-list"))
    return direct_to_template(request, "project_edit.html", extra_context={
        "form": form,
        "nav": {"selected": "projects",},
    })
Exemplo n.º 25
0
def new_project(request):
    if request.method == "POST":
        form = ProjectForm(request.POST or None)
        if form.is_valid():
            if form.save():
                return redirect("/projects")
    else:
        form = ProjectForm()
    data = {"form": form}
    return render(request, "projects/new_project.html", data)
Exemplo n.º 26
0
def add_project(request):
    """
    View to add a project.
    """
    form=ProjectForm(request.POST or None)
    if form.is_valid():
        project=form.save(commit=False)
        project.save()
        return redirect(project)
    return render_to_response('projects/project_form.html', {'form': form}, context_instance=RequestContext(request))
Exemplo n.º 27
0
def update_view(request, id):
    project_form = ProjectForm(request.POST or None,
                               instance=Project.objects.get(id=id))
    if project_form.is_valid():
        project_form.save()
        return redirect('project_index')
    else:
        return HttpResponse(
            """your form is wrong, reload on <a href = "{{ url : 'project_index'}}">reload</a>"""
        )
Exemplo n.º 28
0
def view_project(request, project_id):
    project = get_object_or_404(Project, pk=project_id,
                                course=request.course)
    space_owner = in_course_or_404(project.author.username, request.course)

    if not project.collaboration(request).permission_to('edit',request):
        #LEGACY: try again for legacy projects
        if not project.collaboration(request, sync_group=True).permission_to('edit',request):
            return HttpResponseRedirect(project.get_absolute_url())

    if request.method == "GET":
        if request.META.get('HTTP_ACCEPT','').find('json') >=0:
            return project_json(request, project)
        return project_workspace(request, space_owner, project)

    if request.method == "DELETE":
        project.delete()
        return HttpResponseRedirect(
            reverse('your-records', args=[request.user.username]))

    if request.method == "POST":
        projectform = ProjectForm(request, instance=project,data=request.POST)
        if projectform.is_valid():
            if "Preview" == request.POST.get('submit',None):
                #doesn't send project.author, and other non-exposed fields
                mock_project = projectform.cleaned_data.copy()
                mock_project['attribution_list'] = mock_project['participants']
                mock_project['assignment'] = projectform.instance.assignment()
                mock_project['id'] = project_id
                return project_preview(request, space_owner, mock_project, 
                                       is_participant=True, preview_num=request.GET.get('preview',1))
            
            #legacy and for optimizing queries
            projectform.instance.submitted = (request.POST.get('publish',None) != 'PrivateEditorsAreOwners')
            
            #this changes for version-tracking purposes
            projectform.instance.author = request.user
            projectform.save()

            projectform.instance.collaboration(request, sync_group=True)

            if request.META.get('HTTP_ACCEPT','').find('json') >=0:
                v_num = projectform.instance.get_latest_version()
                return HttpResponse(simplejson.dumps(
                        {'status':'success',
                         'revision':{
                                'id':v_num,
                                'url':reverse('project_version_preview',args=[project_id, v_num]),
                                'public_url':projectform.instance.public_url(),
                                }
                         }, indent=2),
                                    mimetype='application/json')

        redirect_to = '.'
        return HttpResponseRedirect(redirect_to)
Exemplo n.º 29
0
def edit_project(request, project_id):
    project = Project.objects.get(id=project_id)
    if request.method == "POST":
        form = ProjectForm(request.POST, instance=project)
        if form.is_valid():
            if form.save():
                return redirect("/projects/{}".format(project_id))
    else:
        form = ProjectForm(instance=project)
    data = {"project": project, "form": form}
    return render(request, "projects/edit_project.html", data)
Exemplo n.º 30
0
def project_create(request):
    if request.method == 'POST' and request.is_ajax():
        form = ProjectForm(request.POST, request.FILES)
        if form.is_valid():
            project = form.save(commit=False)
            project.owner = request.user
            project.save()
            return HttpResponse(status=201)
        else:
            return render(request, 'projects/includes/_project_form.html', {'form': form})
    return HttpResponse(status=201)
Exemplo n.º 31
0
 def test_form_valid(self):
     user = UserFactory()
     form = ProjectForm(data={'name': 'Hello World!'})
     self.assertTrue(form.is_valid())
     project = form.save(commit=False)
     project.owner = user
     project.save()
     self.assertEqual(project.name, 'Hello World!')
     self.assertEqual(project.owner, user)
     self.assertIsNotNone(project.created)
     self.assertIsNotNone(project.modified)
Exemplo n.º 32
0
	def post(self, request, project_id):

		project = Project.objects.get(pk = project_id)
		form = ProjectForm(request.POST, instance = project)

		if form.is_valid():
			project = form.save()
			messages.success(request, 'Project \'' + project.name + '\' was successfully updated.')
			return redirect('/projects/update/' + project_id)
		else:
			messages.error(request, 'Sorry, but there was a problem with the information you supplied.')
			return render_update(request, form, project_id)
Exemplo n.º 33
0
 def post(self, request):
     form = ProjectForm(request.POST)
     if form.is_valid():
         owner = form.cleaned_data['owner']
         name = form.cleaned_data['name']
         description = form.cleaned_data['description']
         status = form.cleaned_data['status']
         Project.objects.create(owner=owner,
                                name=name,
                                description=description,
                                status=status)
         return HttpResponseRedirect(reverse('project_list'))
Exemplo n.º 34
0
def edit_project(request, slug):
    if request.method == 'POST':
        project = get_object_or_404(Project, slug=slug)
        form = ProjectForm(request.POST, instance=project)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(project.get_absolute_url())

    else:
        project = get_object_or_404(Project, slug=slug)
        form = ProjectForm(instance=project)
    return render_to_response('projects/new_project.html', {'form': form}, context_instance=RequestContext(request))
Exemplo n.º 35
0
def edit_project(request, id):
    project = Project.objects.get(pk=id)
    if request.method == 'POST':
        form = ProjectForm(request.POST, instance=project)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('project_index'))
        else:
            return render(request, 'projects/edit_project.html', {'form': form})
    else:
        form = ProjectForm(instance=project)
        return render(request, 'projects/edit_project.html', {'form': form})
Exemplo n.º 36
0
def prj_create(request):

    if request.method == 'POST':
        form = ProjectForm(request.POST, request.FILES)
        if form.is_valid():
            prj = form.save(user=request.user)
            return HttpResponseRedirect(prj.get_absolute_url())
    else:
        form = ProjectForm()

    var = RequestContext(request, {'form': form})
    return render_to_response('projects/prj_create.html', var)
Exemplo n.º 37
0
def project_new(request):
    """
        add new project
    """
    form = ProjectForm(request.POST or None)
    if form.is_valid():
        name = form.cleaned_data['name']
        creator = request.user
        project = Project()
        project.new(creator, name)
        return HttpResponse("Project Created!")
    return TemplateResponse(request, "projects/project_new.html", {'form': form}) 
Exemplo n.º 38
0
def overview(request, username):
    SecondaryObjectiveFormSet = inlineformset_factory(
        Project,
        SecondaryObjective,
        form=SecondaryObjectiveForm,
        extra=3,
        can_delete=False)
    user = User.objects.get(username=username)
    projects = Project.objects.filter(Q(created_by=user)
                                      | Q(members__id__in=[user.id]),
                                      active=True).distinct()
    resources = Publication.objects.filter(project__in=projects,
                                           user=user,
                                           archived=False)
    if request.method == 'POST':
        project_form = ProjectForm(request.POST)
        objectives_formset = SecondaryObjectiveFormSet(request.POST)

        # if project_form.is_valid() and objectives_formset.is_valid():
        #     project = project_form.save(commit=False)
        #     objectives = objectives_formset.save(commit=False)
        #     project.created_by = request.user
        #     project.save()
        #     for objective in objectives:
        #         objective.project = project
        #         objective.save()
        #
        # else:
        #     data = project_form.errors.as_json()
        #     print("form is not valid", data)
        #     return JsonResponse(data, safe=False, status=400)
    else:
        objectives_formset = inlineformset_factory(
            Project,
            SecondaryObjective,
            form=SecondaryObjectiveForm,
            extra=3,
            can_delete=False,
        )
        # objectives_formset = objectives_formset(initial=SecondaryObjective.objects.all().values())
        objectives_formset = objectives_formset()
        project_form = ProjectForm()

    return render(
        request, 'accounts/profile-overview.html', {
            'user': user,
            "resources": resources,
            "projects": projects,
            "form": ResourceForm(user=request.user),
            "project_form": project_form,
            "objectives_formset": objectives_formset,
        })
def edit_project(request, project_id):
    try:
        project_id = Project.objects.get(id=project_id)
    except User.DoesNotExist:
        raise Http404
    if request.method == 'POST':
        form = ProjectForm(request.POST, instance=project_id)
        if form.is_valid():
            project_id = form.save()
            return HttpResponseRedirect('/profile/')
    else:
        form = ProjectForm(instance=project_id)
    return render_to_response('update_project.html', {'form': form}, context_instance=RequestContext(request))
Exemplo n.º 40
0
Arquivo: views.py Projeto: kpx13/solar
def participate(request):
    c = get_common_context(request)
    if not c['auth']:
        return HttpResponseRedirect('/accounts/register/')
    user = request.user
    profile = user.get_profile()
    if request.method == 'GET':
        if Participant.exist(user):
            return HttpResponseRedirect('/project/%s/' % Participant.get_project(user))
        elif Expert.exist(user):
            c['form'] = None
            c['msg'] = u'Вы эксперт, поэтому не можете принимать участие.'
        else:
            c['form'] = ParticipateForm(initial={'name': user.first_name,
                                             'last_name': user.last_name,
                                             'photo': profile.photo,
                                             'sex': profile.sex,
                                             'date_birth': profile.date_birth,
                                             'school': profile.school,
                                             })
            c['project_form'] = ProjectForm()
    else:
        form = ParticipateForm(request.POST, request.FILES)
        project_form = ProjectForm(request.POST)
        if form.is_valid() and project_form.is_valid():
            user.first_name = form.data['name']
            user.last_name = form.data['last_name']
            user.save()
            if 'photo' in request.FILES:
                profile.photo = request.FILES.get('photo', '')
            profile.sex = form.data.get('sex', '')
            profile.date_birth = form.data['date_birth']
            profile.school = form.data['school']
            profile.save()
            part = Participant(user=user,
                               about=form.data['about'])
            part.save()
            
            pf = project_form.save(commit=False)
            pf.participant = part
            pf.save()
            
            return HttpResponseRedirect('/project/')
        else:
            pass
        
        c['form'] = form
        c['project_form'] = project_form
    c['user_photo'] = profile.photo
    return render_to_response('participate.html', c, context_instance=RequestContext(request))
Exemplo n.º 41
0
def add_project(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)

        if form.is_valid():
            form.instance.token = str(uuid4())
            instance = form.save()
            instance.user.add(request.user)
            return HttpResponseRedirect('/panel/projects/%d' % form.instance.id)

    else:
        form = ProjectForm()

    return TemplateResponse(request, 'panel/project_form.html', {'form': form})
Exemplo n.º 42
0
def new(request):
    if request.method == 'POST':
        f = ProjectForm(request.POST)
        if f.is_valid():
            project = f.save(commit=False)
            project.created_by = request.user
            project.updated_by = request.user
            project.save()
            return HttpResponseRedirect(reverse('project-index'))
    else:
        f = ProjectForm()

    return render_to_response('projects/new.html', { 'form': f },
        context_instance=RequestContext(request))
def project_save(request, project_id):
    project = get_object_or_404(Project, pk=project_id, course=request.course)

    if not project.can_edit(request) or not request.method == "POST":
        return HttpResponseRedirect(project.get_absolute_url())

    # verify user is in course
    in_course_or_404(project.author.username, request.course)

    projectform = ProjectForm(request, instance=project, data=request.POST)
    if projectform.is_valid():

        # legacy and for optimizing queries
        projectform.instance.submitted = \
            request.POST.get('publish', None) != 'PrivateEditorsAreOwners'

        # this changes for version-tracking purposes
        projectform.instance.author = request.user
        projectform.save()

        projectform.instance.collaboration(request, sync_group=True)

        if request.META.get('HTTP_ACCEPT', '').find('json') >= 0:
            v_num = projectform.instance.get_latest_version()
            return HttpResponse(simplejson.dumps({
                'status': 'success',
                'is_assignment': projectform.instance.is_assignment(request),
                'title': projectform.instance.title,
                'revision': {
                    'id': v_num,
                    'public_url': projectform.instance.public_url(),
                    'visibility': project.visibility_short(),
                    'due_date': project.get_due_date()
                }
            }, indent=2), mimetype='application/json')
    else:
        ctx = {'status': 'error', 'msg': ""}
        for key, value in projectform.errors.items():
            if key == '__all__':
                ctx['msg'] = ctx['msg'] + value[0] + "\n"
            else:
                ctx['msg'] = \
                    '%s "%s" is not valid for the %s field.\n Please %s\n' % \
                    (ctx['msg'], projectform.data[key],
                     projectform.fields[key].label,
                     value[0].lower())

        return HttpResponse(simplejson.dumps(ctx, indent=2),
                            mimetype='application/json')
Exemplo n.º 44
0
def CreateProject(request):
    if request.method == "POST":
        if request.user.is_staff:
            projform = ProjectForm(request.POST)
            if projform.is_valid():
                p = Project.objects.create(name = projform.cleaned_data['name'] , progress=0)
                p.save()
                return HttpResponseRedirect('/projects')
            else:
                return render(request , 'new_project.html' , {'errors':True , 'form':projform})
        else:
            return HttpResponseRedirect('/projects')
    else:
        projform = ProjectForm()
        return render(request , 'new_project.html' , {'form' : projform})
Exemplo n.º 45
0
def create_project(request):
    if request.method == 'POST':
        project_form = ProjectForm(request.POST)
        if project_form.is_valid():
            project = project_form.save()
            return HttpResponseRedirect(reverse('project_detail', args=[project.id]))
        else:
            return render(request, 'projects/create_project.html',
                          {'project_form': project_form})
    else:
        project_form = ProjectForm(initial={'widgets': {'owner': forms.HiddenInput},
                                            'owner': request.user})

    return render(request, 'projects/create_project.html',
                  {'project_form': project_form})
Exemplo n.º 46
0
def edit_project(request, projectid):
    names = ['Material Purchase', 'Make Payment', 'Invoices', 'Payments']
    links = [
        '/projects/' + projectid + '/purchases',
        '/projects/' + projectid + '/payments',
        '/projects/' + projectid + '/invoices',
        '/projects/' + projectid + '/allpayments'
    ]
    submenus = create_sub(names, links)
    proj = get_object_or_404(Project, pk=projectid)
    context = {'proj_selected': 'current'}

    if len(request.POST) <= 0:
        data = {
            'name': proj.name,
            'location': proj.location,
            'city': proj.city,
            'owner': proj.owner,
            'start_date': proj.start_date,
            'end_date': proj.end_date
        }
        form = ProjectForm(data)
        context.update({
            'title': 'Update Project Details',
            'form': form,
            'submenus': submenus
        })
        return render(request, "edit.html", context)
    else:
        form = ProjectForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            proj.name = cd.get('name')
            proj.location = cd.get('location')
            proj.city = cd.get('city')
            proj.owner = cd.get('owner')
            proj.start_date = cd.get('start_date')
            proj.end_date = cd.get('end_date')
            proj.save()
            url = reverse('projects')
            return HttpResponseRedirect("%s?success=1" % (url))
        else:
            context.update({
                'title': 'Update Project Details',
                'form': form,
                'submenus': submenus
            })
            return render(request, "edit.html", context)
Exemplo n.º 47
0
def submit_project(request):
    form = ProjectForm()
    add_tier_formset = inlineformset_factory(Project, Tier, extra=0, exclude=[])
    project = form.save(commit=False)

    if request.method == 'POST':
        form = ProjectForm(request.POST, request.FILES)
        if 'add_tier' in request.POST:
            copy = request.POST.copy()
            copy['tier-TOTAL_FORMS'] = int(copy['tier-TOTAL_FORMS'])+ 1
            new_tier = add_tier_formset(copy, prefix='tier', instance=project)
        elif 'submit' in request.POST:
            project = form.save(commit=False)
            if form.is_valid():
                user = request.user

                project.user = user
                project.video = request.FILES['video']
                project.save()

                subject = "Project Submission Notice"
                message = "This is to inform you that your project '" + project.name + "' has been submitted for vetting."
                project_owner = request.user.email


                to_owner_email = EmailMessage(subject, message, [project_owner])
                to_owner_email.send()

                subject = "Project Submission Notice"
                message = "This is to inform you that " + user.userprofile.first_name + " " + user.userprofile.last_name + " has submitted a project named " + project.name + " with you listed as an adviser."
                project_adviser = project.adviser_email


                to_adviser_email = EmailMessage(subject, message, [project_adviser])
                to_adviser_email.send()

            new_tier = add_tier_formset(request.POST, prefix='tier', instance=project)
            if new_tier.is_valid():
                new_tier.save()


            return redirect(project)
    else:
        new_tier = add_tier_formset(prefix='tier',instance=project)

    return render_to_response('add_project.html',
                              {'form': form, 'tier': new_tier},
                              context_instance=RequestContext(request))
Exemplo n.º 48
0
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)

        if form.is_valid():
            try:
                project = Project.objects.filter(
                    liderNome=form.data['liderNome'].upper(),
                    liderTelefone=form.data['liderTelefone'],
                    liderEmail=form.data['liderEmail'].upper(),
                    ativo='SIM')[0]
                formulario = ProjectForm(instance=project)
            except:
                return render(
                    request, 'login.html', {
                        'form':
                        form,
                        'msg':
                        'Projeto não encontrado. Revise as suas informações.'
                    })

            return render(request, 'formProject.html', {'form': formulario})
        else:
            return render(request, 'login.html', {
                'form': form,
                'msg': 'Os dados não são válidos. Revise os campos.'
            })
    else:
        form = LoginForm()
        return render(request, 'login.html', {
            'form': form,
            'msg': 'Erro de login.'
        })
Exemplo n.º 49
0
def new_project(request):
    if request.method == 'POST':
        form = ProjectForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            project = form.save()
            if request.POST.get("role") == "O": 
                project.advisors.add(request.user.get_profile())
            if request.POST.get("role") == "E":
                project.students.add(request.user.get_profile())
            project.save()
            return HttpResponseRedirect(project.get_absolute_url())
    else:
        form = ProjectForm()  
    return render_to_response('projects/new_project.html',
                              {'form': form},
                              context_instance = RequestContext(request))
Exemplo n.º 50
0
 def post(self, request, *args, **kwargs):
     project_form = ProjectForm(request.POST)
     if project_form.is_valid():
         project_form.save()
         return super(AddProjectView, self).post(request, *args, **kwargs)
     else:
         # Redisplay the create project form.
         return render(
             request,
             "projects/project_form.html",
             {
                 "form": ProjectForm,
                 #'error_message': project_form.errors,
                 "error_message": "All the fields are required.",
             },
         )
Exemplo n.º 51
0
 def get_context_data(self, **kwargs):
     context = super(CommentaryCreateView, self).get_context_data(**kwargs)
     context['commentaryForm'] = context.get('form')
     context['project'] = self.project
     context['form'] = ProjectForm(instance=context['project'])
     context['dataset'] = context['project'].project_dataset.first()
     context['datasetForm'] = DatasetForm(instance=context['dataset'])
     return context
Exemplo n.º 52
0
def checkCommunityPartner(request):
    partnerForm = ProjectForm()
    communityParnterName = []
    for object in CommunityPartner.objects.order_by('name'):
        partner = object.name

        if partner not in communityParnterName:
            communityParnterName.append(partner)

    if request.method == 'POST':
        partnerForm = ProjectForm(request.POST)



    # print(projectNames)
    return render(request, 'partners/checkCommunityPartner.html',
                  {'partnerForm': partnerForm, 'partnerNames':communityParnterName})
Exemplo n.º 53
0
def new_project(request):
    names = ['Create New Project', 'OnGoing Projects', 'Completed Projects']
    links = [
        reverse('new_project'),
        reverse('projects'),
        reverse('old_projects')
    ]
    submenus = create_sub(names, links)
    context = {'proj_selected': 'current'}
    if len(request.POST) <= 0:
        form = ProjectForm()
        context.update({
            'form': form,
            'entity': 'Project',
            'submenus': submenus
        })
        return render(request, "new.html", context)
    else:
        form = ProjectForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            url = reverse('projects')
            return HttpResponseRedirect("%s?success=2" % (url))
        else:
            context.update({
                'title':
                'Create New Project',
                'form':
                form,
                'entity':
                'Project',
                'errors':
                'Invalid Entry or required fields not filled'
            })
            return render(request, "new.html", context)
Exemplo n.º 54
0
def createProject(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            form = ProjectForm(request.POST)

            if form.is_valid():
                project_form = form.save(commit=False)
                project_form.save()
                form.save_m2m()

                for _img in request.FILES.getlist('project_images[]'):
                    FileSystemStorage(location='/images')
                    photo = Images(project=project_form, path=_img)
                    photo.save()

                for tag in request.POST["project_tags"].split(","):
                    tag = tag.strip()
                    Tags(project=project_form, tag_name=tag).save()

                # user profile page
                return redirect("project_details", project_form.id)
            else:
                return render(request, 'projects/create_project.html/',
                              {'project_form': form})

        else:

            project_form = ProjectForm(initial={"user": request.user})

            return render(request, 'projects/create_project.html/',
                          {'project_form': project_form})
    else:
        return redirect('login')
Exemplo n.º 55
0
 def get(self, request):
     my_projects = Project.objects.current_user_projects(request.user)
     form = ProjectForm()
     return render(
         request, 'projects/projects.html', {
             'num_projects': Project.objects.count(),
             'my_projects': my_projects,
             'form': form
         })
Exemplo n.º 56
0
def create_project(request):
    context = {}

    if request.method == 'POST':
        try:
            form = ProjectForm(request.POST)
            new_project = form.save(commit=False)
            new_project.user = request.user
            new_project.save()
            return redirect('project:my_projects')
        except ValueError:
            context["form"] = ProjectForm()
            context['error'] = 'bad data try again'

    else:
        context['form'] = ProjectForm()

    return render(request, 'projects/create.html', context)
Exemplo n.º 57
0
def create_project(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            project = form.save(commit=False)
            project.created_by = request.user
            project.save()
            members_queryset = form.cleaned_data.get("members")
            for member in members_queryset.all():
                Membership.objects.create(user=member, project=project)
            return render(request, 'projects/includes/_project-card.html', {
                "project": project,
            })
        else:
            data = form.errors.as_json()
            return JsonResponse(data, safe=False, status=400)
    else:
        return HttpResponse(request.method)
Exemplo n.º 58
0
def add_project_view(request):
    if request.user.is_authenticated():
        if request.POST:
            form = ProjectForm(request.POST)
            if form.is_valid():
                #f2 =request.POST
                data = form.cleaned_data
                try:
                    p = Project.objects.get(name=data['name'])
                    messages.add_message(request, messages.ERROR,
                                         " invalid form")
                    return (redirect(reverse('Home:Projects:add_project')))
                except:
                    pass
                td = data['end_date'] - data['start_date']
                if td.total_seconds() >= 0:
                    #    form.save
                    #if data['end_date'] >= data['start_date']:
                    project = Project()
                    project.name = data['name']
                    project.description = data['description']
                    project.start_date = data['start_date']
                    project.end_date = data['end_date']
                    project.user = User.objects.get(
                        username=request.user.username)
                    project.save()
                #    messages.add_message(request, messages.INFO, " Project Added!!")
                else:
                    messages.add_message(request, messages.ERROR,
                                         " end date is less than start date!")
                    return (redirect(reverse('Home:Projects:add_project')))
                return (redirect(reverse('Home:Projects:manager')))
            else:
                messages.add_message(request, messages.ERROR, " invalid form")
                return (redirect(reverse('Home:Projects:add_project')))
        else:
            form = ProjectForm()
            dict = {}
            dict['form'] = form
            return render_to_response('managers/add_project.html',
                                      dict,
                                      context_instance=RequestContext(request))
    else:
        return redirect(reverse('Login:login'))
Exemplo n.º 59
0
def new_project(request):
    if request.method == 'POST':
        project = Project()
        form = ProjectForm(request.POST, instance=project)
        if form.is_valid():
            form.save(commit=False)
            project.user = request.user
            project.admingroup = request.organization.admingroup
            project.save()
            form.save_m2m()
            return HttpResponseRedirect(project.get_absolute_url())

    else:
        project = Project()
        form = ProjectForm(instance=project)
    return render_to_response('projects/new_project.html', {'form': form},
                              context_instance=RequestContext(request))
Exemplo n.º 60
0
 def get(self, request):
     template_name = 'capturista/home.html'
     projects = request.user.projects.all()
     form = ProjectForm()
     form2 = ProfileForm()
     context = {
         'section': 'alta',
         'form': form,
         'form2': form2,
         'num_projects': projects.count()
     }
     return render(request, template_name, context)