def test_is_ending_soon_with_project_ending_soon(self): """ is_ending_soon() should return True if the project is ending soon. """ project = Project(end_date = timezone.now() + datetime.timedelta(days=3)) self.assertEqual(project.is_ending_soon(), True, "The project is ending within the week, but that isn't soon enough apparently.")
def post(self, request): try: serializer = self.serializer_class(data=request.data) if serializer.is_valid(): data = serializer.data user = request.user if not user: return JsonResponse({'error': 'User Not Found'}, status=status.HTTP_400_BAD_REQUEST) location = University.objects.get(id=data['location']) project = Project(user=user, name=data['name'], location=location, startDate=data['startDate'], endDate=data['endDate'], description=data['description']) project.save() count = ProjectCount(project=project) count.save() for cat in data['categories']: category = Category.objects.get(id=cat) category_obj = ProjectCategory(category=category, project=project) category_obj.save() created = ProjectParticipant(student=user, project=project, isLeader=True) created.save() return JsonResponse({'data': project.id}, status=status.HTTP_201_CREATED) else: return JsonResponse({'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return JsonResponse({'error': repr(e)}, status=status.HTTP_400_BAD_REQUEST)
def save_project(request): workspace_id = request.session.get(SESSION_WORKSPACE_KEY_NAME) if (request.method == 'POST'): id = request.POST.get('project-id') title = request.POST.get('project-title') description = request.POST.get('project-description') color = request.POST.get('project-color') if (id): # update existing_project = Project.objects.filter(id=id)[0] existing_project.title = title existing_project.description = description existing_project.color = color existing_project.save() else: workspace = Workspace.objects.filter(id=workspace_id)[0] new_project = Project(title=title, description=description, color=color, workspace=workspace) new_project.save() return redirect('projects') else: return redirect('projects')
def test_is_ending_soon_with_project_not_ending_soon(self): """ is_ending_soon() should return False if the project isn't ending within the next week. """ project = Project(end_date = timezone.now() + datetime.timedelta(days=30)) self.assertEqual(project.is_ending_soon(), False, "Soon is a relative concept anyway...")
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))
def handle(self, *args, **options): from pygithub3 import Github from projects.models import Project from django.conf import settings gh = Github(login=settings.GITHUB_USER, password=settings.GITHUB_PASSWORD) repos = gh.repos.list(user="******").all() for repo in repos: try: proj = Project.objects.get(external_id=repo.id) proj.name = repo.name proj.description = repo.description proj.url = repo.html_url proj.is_fork = repo.fork if repo.pushed_at: proj.updated = repo.pushed_at else: proj.updated = repo.updated_at proj.save() except Project.DoesNotExist: proj = Project( name=repo.name, description=repo.description, code_url=repo.html_url, is_fork=repo.fork, external_id=repo.id, project_type=1, status=1, ) proj.save()
def setUp(self): self.client = Client() self.user = User.objects.create_user('john', '*****@*****.**', 'johnpassword') self.p1 = Project(name="project1", code="pj1") self.p1.save() self.p2 = Project(name="project2", code="pj2") self.p2.save()
def project_list(request): if request.method == 'GET': projects = Project.objects.all() projects_serializer = ProjectSerializer(projects, many=True) return JsonResponse(projects_serializer.data, safe=False) elif request.method == 'POST': try: project_data = JSONParser().parse(request) name = project_data.get('name', 'default project name') description = project_data.get('description', 'default project description') duration = project_data.get('duration', datetime.datetime.now()) if duration == '': duration = datetime.datetime.now() project = Project(name=name, description=description, duration=duration) project.save() return HttpResponse(status=status.HTTP_201_CREATED) except: return HttpResponse(status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': Project.objects.all().delete() return HttpResponse(status=status.HTTP_204_NO_CONTENT)
class TestCanonical(TestCase): def setUp(self): self.p = Project( name='foo', repo='http://github.com/ericholscher/django-kong', ) self.p.save() def test_canonical_clean(self): # Only a url self.p.canonical_url = "djangokong.com" self.assertEqual(self.p.clean_canonical_url, "http://djangokong.com/") # Extra bits in the URL self.p.canonical_url = "http://djangokong.com/en/latest/" self.assertEqual(self.p.clean_canonical_url, "http://djangokong.com/") self.p.canonical_url = "http://djangokong.com//" self.assertEqual(self.p.clean_canonical_url, "http://djangokong.com/") # Subdomain self.p.canonical_url = "foo.djangokong.com" self.assertEqual(self.p.clean_canonical_url, "http://foo.djangokong.com/") # Https self.p.canonical_url = "https://djangokong.com//" self.assertEqual(self.p.clean_canonical_url, "https://djangokong.com/") self.p.canonical_url = "https://foo.djangokong.com//" self.assertEqual(self.p.clean_canonical_url, "https://foo.djangokong.com/") """
def add_project(request): if request.method == 'POST': payload = json.loads(request.body) payload.reverse() try: for item in payload: title = item['title'] abstract = item['abstract'] description = item['description'] code = item['code'] deployment = item['deployment'] project = Project(title=title, abstract=abstract, description=description, code=code, deployment=deployment) project.save() response = json.dumps([{'Success': 'Success!'}]) except: response = json.dumps([{'Error': 'Project could not be added!'}]) return HttpResponse(response, content_type='text/json') elif request.method == 'GET': return get_all_projects(request)
def create_project(request): if request.method == 'POST': if request.POST["title"]: title = request.POST["title"] description = request.POST["description"] if title: try: project = Project.objects.get(title=title) data = {'status': "error", "message": "project already exist"} return JsonResponse(data) except Project.DoesNotExist: project = Project(title=title, detail=description) project.save() language = Language() language.language_id = "en" language.project = project language.description = "English" language.save() data = {'status': "success", "message": "successfully created project", "project": project.get_data()} return HttpResponseRedirect("/projects/" + str(project.id) + "/catalogue/") else: data = {'status': "error", "message": "Please enter the title"} return HttpResponse(json.dumps(data), content_type="application/json") else: return HttpResponseRedirect("/projects/") else: data = {'status': "error", "message": "It is not a POST request"} return HttpResponse(json.dumps(data), content_type="application/json")
def test_is_completed_when_completed(self): """ was_completed() should return True if the project in question has been flagged as completed. """ completed_project = Project(is_completed = True) self.assertEqual(completed_project.was_completed(), True, "is_completed was just a suggestion, right?")
def learn(request): projects = Project.objects.filter(not_listed=False, archived=False, under_development=False, deleted=False) if 'school' in request.GET: projects = projects.filter(school__slug=request.GET['school']) if 'featured' in request.GET: featured = request.GET['featured'] if featured == 'staff': projects = projects.filter(featured=True) elif featured == 'community': projects = projects.filter(community_featured=True) elif featured == 'fresh': one_week = datetime.datetime.now() - datetime.timedelta(weeks=1) projects = projects.filter(created_on__gte=one_week) if 'lang' in request.GET: projects = projects.filter(language=request.GET['lang']) if 'tag' in request.GET: projects = Project.get_tagged_projects(request.GET['tag'], projects) context = { 'projects': projects, 'schools': School.objects.all(), 'popular_tags': Project.get_popular_tags(), 'tags_form': project_forms.ProjectsTagSearch() } context.update(get_pagination_context(request, projects, 24)) return render_to_response('projects/learn.html', context, context_instance=RequestContext(request))
def setUp(self): self.client = Client() self.locale = 'en' django_user = User( username=self.test_username, email=self.test_email, ) self.user = create_profile(django_user) self.user.set_password(self.test_password) self.user.save() self.project = Project( name='Reply Project', short_description='This project is to test replies', long_description='No really, its good', ) self.project.save() participation = Participation(project=self.project, user=self.user, organizing=True) participation.save() self.page = Page(author=self.user, project=self.project, title='task title', sub_header='Tagline', content='Content', index=2) self.page.save()
def setUp(self): self.client = Client() self.locale = 'en' django_user = User( username=self.test_username, email=self.test_email, ) self.user = create_profile(django_user) self.user.set_password(self.test_password) self.user.save() self.project = Project(name='My Cool Project', short_description='This project is awesome', long_description='No really, its good', ) self.project.save() participation = Participation(project=self.project, user=self.user, organizing=True) participation.save() for i in xrange(3): page = Page(author=self.user, project=self.project, title='Old Title %s' % i, sub_header='Old Tagline %s' % i, content='Old Content %s' % i, index=2*(i+1)) page.save()
def test_should_return_identities_for_an_environment(self): client = self.set_up() # Given identifierOne = 'user1' identifierTwo = 'user2' organisation = Organisation(name='ssg') organisation.save() project = Project(name='project1', organisation=organisation) project.save() environment = Environment(name='environment1', project=project) environment.save() identityOne = Identity(identifier=identifierOne, environment=environment) identityOne.save() identityTwo = Identity(identifier=identifierTwo, environment=environment) identityTwo.save() # When response = client.get('/api/v1/environments/%s/identities/' % environment.api_key) # Then self.assertEquals(response.data['results'][0]['identifier'], identifierOne) self.assertEquals(response.data['results'][1]['identifier'], identifierTwo)
def create(): form_class = form_manager.get_form_class("config_form") form = form_class(CombinedMultiDict((request.files, request.form))) if form.validate_on_submit(): f = form.image.data # Make sure the saved image is filename is unique filename = secure_filename(unique_name_encoding(f.filename)) f.save(os.path.join(config.get("PROJECTS", "upload_folder"), filename)) # Remove special fields if form.__contains__("csrf_token"): form._fields.pop("csrf_token") form._fields.pop("image") # Save new instance new_instance = { key: field.data for key, field in form.__dict__.items() if hasattr(field, "data") } new_instance["image"] = filename entity = Project(**new_instance) entity_id = entity.save() # Update user with new instance current_user.projects.append(entity_id) current_user.save() url = url_for("projects.show", object_id=entity_id, _external=True) flash( "Your submission has been received," " your metadata can be found at: " + url, "success", ) return redirect(url) return render_template("projects/create_project.html", form=form)
def test_loading_search_page(self): self.user = User.objects.get(username="******") self.project = Project(name="test") self.project.save() url = self.client.get('/search/?q=test') self.assertEqual(url.status_code, 200) self.assertTemplateUsed(url, 'projects.html')
def test_ml_backend_connections( business_client, label_config, connection_model_names_and_schemas, total_expected_connections, create_label_config_form_onboarding ): if create_label_config_form_onboarding: project = Project(title='test_ml_backend_connections', label_config=label_config) project.created_by = business_client.user project.save() else: project = Project.objects.create( title='test_ml_backend_connections', created_by=business_client.user) r = business_client.patch( f'/api/projects/{project.id}/', data=json.dumps({'label_config': label_config}), content_type='application/json', ) assert r.status_code == 200 conns = MLBackendConnection.objects.filter(project=project.id) assert conns.count() == total_expected_connections for conn in conns: assert conn.ml_backend.name in connection_model_names_and_schemas schemas = connection_model_names_and_schemas[conn.ml_backend.name] if isinstance(schemas, list): assert any(schema == conn.schema for schema in schemas) else: assert schemas == conn.schema
def test_is_completed_when_not_completed(self): """ was_completed() should return False if the project in question has not been flagged as completed. """ completed_project = Project(is_completed = False) self.assertEqual(completed_project.was_completed(), False, "Are you done? You look done. Yeah, you're done.")
def testEditProject(self): project = Project(name="test") project.save() self.client.login(username='******', password='******') r = self.client.get(reverse("projects-edit", args=[project.pk])) self.assertEquals(200, r.status_code)
def add_project(request): if request.method == 'POST': form = forms.ProjectForm(request.POST) if form.is_valid(): eco_name = form.cleaned_data['eco_name_state'] eco_orm = None project_name = form.cleaned_data['project_name'] try: project_orm = Project.objects.get(name=project_name) msg = 'Project \"%s\" already exists' % project_name except Project.DoesNotExist: project_orm = Project(name=project_name) project_orm.save() msg = 'Project \"%s\" has been added' % project_name if eco_name: eco_orm = Ecosystem.objects.get(name=eco_name) eco_orm.projects.add(project_orm) eco_orm.save() context = EditorState(projects=[project_name], project_id=project_orm.id, form=form, msg=msg) return shortcuts.render(request, 'projects/editor.html', build_forms_context(context)) else: # TODO: Show error raise Http404 # if a GET (or any other method) we'll create a blank form else: # TODO: Show error return shortcuts.render(request, 'projects/editor.html', build_forms_context())
def read_directory(path=base_path): for dir in Path(path).iterdir(): if dir.is_dir(): if not Project.objects.filter(title=dir.stem): project = Project(title=dir.stem) project.save() get_pages(dir.stem)
def project_new(request, user_id): user = User.objects.get(pk=user_id) if request.method == 'POST': if request.is_ajax(): project_name = request.POST.get('project_name') start_date = request.POST.get('start_date') end_date = request.POST.get('end_date') response_data = {} project = Project(name=project_name, start_date=start_date, end_date=end_date, user=user) project.save() response_data['project_name'] = project.name response_data['start_date'] = project.start_date response_data['end_date'] = project.end_date response_data['user_id'] = user.id return JsonResponse(response_data) # def project_new(request): # if request.method == "POST": # form = ProjectForm(request.POST or None) # if form.is_valid(): # project = form.save(commit=False) # project.user = request.user # project.save() # return HttpResponseRedirect('/login/') # else: # form = ProjectForm() # return render(request, 'projects/home.html', {'form':form})
def create_account(request, token, ip, end, title, account, id, quota): """Create account.""" # Poor-man's authentication: if token != settings.J["ACTION_TOKEN"]: return JsonResponse({}) # Get the IP for the project: proj_ip = get_ip(ip) # Starting and ending dates: tz = pytz.timezone("Europe/Madrid") start_date = datetime.now(tz) end_date = datetime.strptime(end, "%Y%m%d%H%M") end_date = timezone.make_aware(end_date, timezone=tz) # Create Project object: project = Project(ip=proj_ip, name=title, user=account, proj_id=id.replace("-", "/")) project.save() # Create Period object: period = Period(proj=project, start=start_date, end=end_date, quota=quota, status="active") period.save() # Success: return JsonResponse({"response": True})
def projectAdded(request): if request.user.is_authenticated: title = request.GET['title'] body = request.GET['body'] #c = request.GET['c'] #cSharp = request.GET['cSharp'] skills = formSkillsDictFromRequest(request) skillsString = str(skills) university = request.GET['university'] data = { 'title': title, 'body': body, 'skills': str(parseSkillsStringIntoArray(skillsString)), 'university': university } newProject = Project(title=title, pub_date=datetime.datetime.now(), body=body, skills=skillsString, university=university, owner=request.user) newProject.save() return render(request, 'projects/projectAdded.html', data) else: return render(request, 'projects/createProjectError.html')
def validate_label_config(self, value): if self.instance is None: # No project created yet Project.validate_label_config(value) else: # Existing project is updated self.instance.validate_config(value) return value
def make_api_project(project_data): from projects.models import Project for key in ['users', 'resource_uri', 'absolute_url', 'downloads', 'main_language_project', 'related_projects']: if key in project_data: del project_data[key] project = Project(**project_data) project.save = _new_save return project
def create_pinax_project(user, line): project = Project() project.creator = user project.name = line["project"] project.slug = slugify(line["project"]) project_created_msg = _("Found more than one project, you are on, with same name. New project will be created.") project_created_bool = True return (project, project_created_msg, project_created_bool)
def test_is_ending_soon_with_completed_project(self): """ is_ending_soon() should return False in cases where it has already ended. """ completed_project = Project(end_date = timezone.now() - datetime.timedelta(days=1), is_completed = True) self.assertEqual(completed_project.is_ending_soon(), False, "It seems to think a completed project is ending soon...")
def test_add_project(self): project = Project(name='Test', category='Test Cat', description='Test Desc') project.save() self.assertEqual(project.name, "Test") self.assertEqual(project.category, "Test Cat") self.assertEqual(project.description, "Test Desc")
def get(self, request, *args, **kwargs): tesis_project = Project( "Companion Robot", "The Companion Robot based on Kinect Sensor is my Bachelor’s degree project. Together with my mate we built a wheeled robot capable of visually following a person around, while carrying a 5Kg payload. The people tracking system was made possible thanks to Microsoft’s Kinect sensor and the Kinect SDK. The developed human shape recognition program ran on a on-board laptop computer and the main control program on a Microcontroller chip. The setup process and remote control was available through an android mobile app. (2012)", "https://drive.google.com/uc?export=view&id=1zBm0xsbjL5vDqrEA40hW4-rUJY_DKWcg", "", "https://www.youtube.com/watch?v=0gv6BbJWOB8", "http://bibdigital.epn.edu.ec/handle/15000/17140", ) celebrar_project = Project( "celebrar.vip", "Celebrar.vip is a Django based site meant to host web pages for events, such as weddings or anniversaries. The current functionalities of an event web page is to display further information about it in a aesthetic manner and to offer a RSVP channel for the guests. The site is structured as a Django project with Django apps for each event web page. Although each event is particular, work is being done to build the apps in a way that can be easily customizable for each single event. (2018)", "https://drive.google.com/uc?export=view&id=1bIm204RsBTYn-4vqwY7ASJaKT_TSNiez", "https://github.com/alejandromesias/celebrar_py", "http://www.celebrar.vip/modelapp_a", ) sspot_project = Project( "SSPOT Parking app", "Sspot is a young start-up that strives to help Quito with its car parking issues. Sspot Parking is a mobile app that can tell drivers where parking places are based on their location or destination. I have been responsible for the development of the native Front-End apps for both Android and iOS, and I have also been involved in integrating them to the Node.js backend through the REST API. (2017)", "https://drive.google.com/uc?export=view&id=1k4Wf66crtk8oWqHn_7_pxayAzfhYqDyF", "", "https://play.google.com/store/apps/details?id=com.sspot.www.sspotparkin&hl=en", "http://www.sspot-app.com/conductores", ) personal_project = Project( "alejandromesias.com", "This very same site. It has been built using Django and introducing first steps in TDD through python’s unittest library and functional testing with selenium. (2018)", "https://drive.google.com/uc?export=view&id=1s8_qee09spgnfBfYkLVUNDPh48fT9-9a", "https://github.com/alejandromesias/personal_site", "http://www.alejandromesias.com", ) engtranslator_project = Project( "engineering translators", "Engineering translators is a web app developed for a group of translators freelancers who had a glossary of technical terms translated to spanish and wanted to display it on the internet. It was developed as a Django project. Of special interest are the relationships between terms, themes, chapters, related terms, synonyms, etc, that needed to be addressed when defining the models for the Database.(2017)", "https://drive.google.com/uc?export=view&id=1NYKOoIfKtA6SBjDrj1SSnZAfYD3w6rTk", "https://github.com/alejandromesias/engtranslators", "http://amesias.pythonanywhere.com/", ) projects_list = [ tesis_project, celebrar_project, sspot_project, personal_project, engtranslator_project, ] context = { 'projects_list': projects_list, } return self.render_to_response(context)
def test_complete_project_when_already_completed(self): """ complete_project() should do nothing if the project in question has already been completed. """ old_end_date = timezone.now() - datetime.timedelta(days=1) completed_project = Project(end_date = old_end_date, is_completed = True) completed_project.complete_project() self.assertEqual(completed_project.end_date, old_end_date, "Completing already finished projects is most effective!")
def update(self, instance: Project, validated_data: dict) -> Project: attribute_data = validated_data.pop("attribute_data", {}) with transaction.atomic(): self.log_updates_attribute_data(attribute_data) if attribute_data: instance.update_attribute_data(attribute_data) return super(ProjectSerializer, self).update(instance, validated_data)
def make_api_project(project_data): from projects.models import Project for key in ["users", "resource_uri", "absolute_url", "downloads", "main_language_project", "related_projects"]: if key in project_data: del project_data[key] project = Project(**project_data) project.save = _new_save return project
def add_project(name, ongoing, startdate='', githuburl='', short_description='', more_info_button_text='', long_description=''): p = Project(name=name, ongoing=ongoing, short_description=short_description, more_info_button_text=more_info_button_text, long_description=long_description) if startdate: p.startdate = startdate if githuburl: p.githuburl = githuburl p.save() return p
def _format_primary_key_data(self, request): """ Format fields that are primary key related so that they may work with DRF """ fields = ['fabric', 'items'] for f in [('customer', Customer), ('project', Project), ('employee', User)]: try: pass #request.data[f[0]] = f[1].objects.get(pk=request.data[f[0]]['id']) except (AttributeError, KeyError, IndexError) as e: pass for field in fields: if field in request.data: if 'id' in request.data[field]: request.data[field] = request.data[field]['id'] if field == 'items': for index, item in enumerate(request.data['items']): try: request.data['items'][index]['fabric'] = item[ 'fabric']['id'] except (KeyError, TypeError): pass try: request.data['items'][index]['product'] = { 'id': item['id'] } del request.data['items'][index]['id'] except KeyError as e: request.data['items'][index]['product'] = { 'id': 10436 } """ try: request.data['items'][index]['image'] = item['image']['id'] except (KeyError, TypeError) as e: request.data['items'][index]['image'] = None """ elif field == 'project': try: if "codename" in request.data[ 'project'] and "id" not in request.data[ 'project']: project = Project( codename=request.data['project']['codename']) project.save() request.data['project'] = project.id except TypeError: pass return request
def _format_primary_key_data_for_put(self, request): """ Format fields that are primary key related so that they may work with DRF """ project = None room = None fields = ['items'] for field in fields: if field in request.data: try: if 'id' in request.data[field]: request.data[field] = request.data[field]['id'] except TypeError: pass if field == 'items': for index, item in enumerate(request.data['items']): try: request.data['items'][index]['fabric'] = item['fabric']['id'] except (KeyError, TypeError): pass try: request.data['items'][index]['image'] = item['image']['id'] except (KeyError, TypeError) as e: request.data['items'][index]['image'] = None # Create a project if it does not exist elif field == 'project': try: project = Project.objects.get(pk=request.data[field]['id']) except KeyError as e: project = Project(codename=request.data[field]['codename']) project.save() request.data[field]['id'] = project.id except TypeError as e: pass # Create a room if it does not exist elif field == 'room': try: room = Room.objects.get(pk=request.data[field]['id']) except (KeyError, AttributeError) as e: room = Room(description=request.data[field]['description'], project=project) room.save() request.data[field]['id'] = room.id except TypeError as e: pass return request
def clone(request): user = request.user.get_profile() if request.method == 'POST': form = project_forms.CloneProjectForm(request.POST) if form.is_valid(): base_project = form.cleaned_data['project'] project = Project(name=base_project.name, kind=base_project.kind, short_description=base_project.short_description, long_description=base_project.long_description, clone_of=base_project) project.save() act = Activity(actor=user, verb=verbs['post'], scope_object=project, target_object=project) act.save() participation = Participation(project=project, user=user, organizing=True) participation.save() new_rel, created = Relationship.objects.get_or_create(source=user, target_project=project) new_rel.deleted = False new_rel.save() detailed_description = Page(title=_('Full Description'), slug='full-description', content=base_project.detailed_description.content, listed=False, author_id=user.id, project_id=project.id) detailed_description.save() project.detailed_description_id = detailed_description.id sign_up = Page(title=_('Sign-Up'), slug='sign-up', content=base_project.sign_up.content, listed=False, editable=False, author_id=user.id, project_id=project.id) sign_up.save() project.sign_up_id = sign_up.id project.save() tasks = Page.objects.filter(project=base_project, listed=True, deleted=False).order_by('index') for task in tasks: new_task = Page(title=task.title, content=task.content, author=user, project=project) new_task.save() links = Link.objects.filter(project=base_project).order_by('index') for link in links: new_link = Link(name=link.name, url=link.url, user=user, project=project) new_link.save() project.create() messages.success(request, _('The %s has been cloned.') % project.kind.lower()) return http.HttpResponseRedirect(reverse('projects_show', kwargs={ 'slug': project.slug, })) else: messages.error(request, _("There was a problem cloning the study group, course, ...")) else: form = project_forms.CloneProjectForm() return render_to_response('projects/project_clone.html', { 'form': form, 'clone_tab': True, }, context_instance=RequestContext(request))
def test_complete_project_when_not_already_completed(self): """ complete_project() should update end_date and set is_completed flag if the project hasn't already been completed. """ project = Project() self.assertEqual(project.end_date, (timezone.now() + datetime.timedelta(days=7)).date()) self.assertEqual(project.is_completed, False) project.complete_project() self.assertEqual(project.end_date, timezone.now().date()) self.assertEqual(project.is_completed, True, "It seems we've ended but not completed. We must have just given up...")
def _format_primary_key_data_for_put(self, request): """ Format fields that are primary key related so that they may work with DRF """ fields = ['fabric', 'items'] for f in [('customer', Customer), ('project', Project), ('employee', User)]: try: pass#request.data[f[0]] = f[1].objects.get(pk=request.data[f[0]]['id']) except (AttributeError, KeyError, IndexError) as e: pass for field in fields: if field in request.data: try: if 'id' in request.data[field]: request.data[field] = request.data[field]['id'] except TypeError: if field == 'acknowledgement': request.data[field] = None if field == 'items': for index, item in enumerate(request.data['items']): try: request.data['items'][index]['fabric'] = item['fabric']['id'] except (KeyError, TypeError): pass if 'product' not in request.data['items'][index]: try: request.data['items'][index]['product'] = {'id': item['id']} del request.data['items'][index]['id'] except KeyError as e: request.data['items'][index]['product'] = {'id': 10436} """ try: request.data['items'][index]['image'] = item['image']['id'] except (KeyError, TypeError) as e: request.data['items'][index]['image'] = None """ elif field == 'project': try: if "codename" in request.data['project'] and "id" not in request.data['project']: project = Project(codename=request.data['project']['codename']) project.save() request.data['project'] = project.id except TypeError: pass return request
def setUp(self): p = Project(name="Project Test") p.set_repo_pwd(self.test_repo_pass) p.save() p = Project(name="Project Test 2") p.enabled = False p.save()
class AuthenticatedAPITestCase(APITestCase): def setUp(self): super().setUp() self.project = Project(name="TestProject", private_key="secret") self.project.save() self.headers = { 'HTTP_PUBLIC_KEY': self.project.id, 'HTTP_PRIVATE_KEY': self.project.private_key }
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})
def test_project_save(self): agency = Agency(name='General Services Administration') agency.save() accounting_code = AccountingCode(agency=agency) accounting_code.save() project = Project(accounting_code=accounting_code, name="Test Project") project.save() retrieved = Project.objects.get(pk=project.pk) self.assertEqual(retrieved.name, "Test Project")
def save_project(request, manager): project_version_name = request.get('default-version-name') version = ProjectVersion(label=project_version_name, order=1) version.put() project = Project(name=request.get('name'), description=request.get('description'), manager=manager, current_version=version, versions=[version.key()]) project.put() return project
def testAddProject(self): project = Project(name="test") project.save() project_url = ProjectURL() project_url.url = "badapp.org" project_url.stage = "dev" project_url.project = project project_url.save() self._addError() assert Group.objects.count() == 1 assert Group.objects.all()[0].project_url == project_url
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'))
def import_from_old_site(request): user = request.user.get_profile() if request.method == 'POST': form = project_forms.ImportProjectForm(request.POST) if form.is_valid(): course = form.cleaned_data['course'] #CS - too much logic in view project = Project(name=course['name'], kind=course['kind'], short_description=course['short_description'], long_description=course['long_description'], imported_from=course['slug']) project.save() act = Activity(actor=user, verb=verbs['post'], scope_object=project, target_object=project) act.save() participation = Participation(project=project, user=user, organizing=True) participation.save() new_rel, created = Relationship.objects.get_or_create(source=user, target_project=project) new_rel.deleted = False new_rel.save() if course['detailed_description']: detailed_description_content = course['detailed_description'] else: detailed_description_content = render_to_string( "projects/detailed_description_initial_content.html", {'project': project}) detailed_description = Page(title=_('Full Description'), slug='full-description', content=detailed_description_content, listed=False, author_id=user.id, project_id=project.id) detailed_description.save() project.detailed_description_id = detailed_description.id sign_up = Signup(between_participants=course['sign_up'], author_id=user.id, project_id=project.id) sign_up.save() project.save() for title, content in course['tasks']: new_task = Page(title=title, content=content, author=user, project=project) new_task.save() for name, url in course['links']: new_link = Link(name=name, url=url, user=user, project=project) new_link.save() project.create() messages.success(request, _('The %s has been imported.') % project.kind.lower()) return http.HttpResponseRedirect(reverse('projects_show', kwargs={ 'slug': project.slug, })) else: msg = _("Problem importing the study group, course, ...") messages.error(request, msg) else: form = project_forms.ImportProjectForm() return render_to_response('projects/project_import.html', { 'form': form, 'import_tab': True}, context_instance=RequestContext(request))
def clone(request): user = request.user.get_profile() if request.method == "POST": form = project_forms.CloneProjectForm(request.POST) if form.is_valid(): base_project = form.cleaned_data["project"] project = Project( name=base_project.name, category=base_project.category, other=base_project.other, other_description=base_project.other_description, short_description=base_project.short_description, long_description=base_project.long_description, clone_of=base_project, ) project.save() act = Activity(actor=user, verb=verbs["post"], scope_object=project, target_object=project) act.save() participation = Participation(project=project, user=user, organizing=True) participation.save() new_rel, created = Relationship.objects.get_or_create(source=user, target_project=project) new_rel.deleted = False new_rel.save() detailed_description = Page( title=_("Full Description"), slug="full-description", content=base_project.detailed_description.content, listed=False, author_id=user.id, project_id=project.id, ) detailed_description.save() project.detailed_description_id = detailed_description.id base_sign_up = base_project.sign_up.get() sign_up = Signup( public=base_sign_up.public, between_participants=base_sign_up.between_participants, author_id=user.id, project_id=project.id, ) sign_up.save() project.save() tasks = Page.objects.filter(project=base_project, listed=True, deleted=False).order_by("index") for task in tasks: new_task = Page(title=task.title, content=task.content, author=user, project=project) new_task.save() links = Link.objects.filter(project=base_project).order_by("index") for link in links: new_link = Link(name=link.name, url=link.url, user=user, project=project) new_link.save() project.create() messages.success(request, _("The %s has been cloned.") % project.kind.lower()) return http.HttpResponseRedirect(reverse("projects_show", kwargs={"slug": project.slug})) else: messages.error(request, _("There was a problem cloning the study group, course, ...")) else: form = project_forms.CloneProjectForm() return render_to_response( "projects/project_clone.html", {"form": form, "clone_tab": True}, context_instance=RequestContext(request) )
def test_messaging_user_following_project(self): project = Project( name='test project', short_description='abcd', long_description='edfgh', created_by=self.user) project.save() Relationship(source=self.user_two, target_project=project).save() form = ComposeForm(data={ 'recipient': self.user_two, 'subject': 'Foo', 'body': 'Bar', }, sender=self.user) self.assertTrue(form.is_bound) self.assertTrue(form.is_valid())