コード例 #1
0
ファイル: tests.py プロジェクト: uncompiled/tock
    def setUp(self):
        agency = Agency(name='General Services Administration')
        agency.save()
        user = User.objects.create(username='******',
                                   first_name='aaron',
                                   last_name='snow')
        accounting_code = AccountingCode(code='abc',
                                         agency=agency,
                                         office='18F',
                                         billable=True)
        accounting_code.save()

        self.project = Project(accounting_code=accounting_code,
                               name='Test Project',
                               start_date='2016-01-01',
                               end_date='2016-02-01',
                               agreement_URL='https://thisisaurl.com',
                               project_lead=user)
        self.project.save()

        self.project_no_url = Project(accounting_code=accounting_code,
                                      name='Test_no_url Project',
                                      start_date='2016-02-01',
                                      end_date='2016-02-02',
                                      agreement_URL='',
                                      project_lead=user)
        self.project_no_url.save()

        self.project_no_lead = Project(accounting_code=accounting_code,
                                       name='Test_no_url Project',
                                       start_date='2016-02-01',
                                       end_date='2016-02-02',
                                       agreement_URL='https://thisisaurl.com',
                                       project_lead=None)
        self.project_no_lead.save()
コード例 #2
0
def Create(request):

    if request.method == "GET":
        project = Project(None)
        category = Category.objects.all()
        return render(request, 'projects/add.html', {'new_project': project, 'category': category})
    else:
        project = Project(
            title=request.POST.get('title'),
            details=request.POST.get('details'),
            category_id=request.POST.get('category'),
            total_target=request.POST.get('total_target'),
            start_date=request.POST.get('s_date'),
            end_date=request.POST.get('e_date'),
            owner_id=request.user.id
        )
        if project.clean():
            project.save()
            uploadImages(request, Project.objects.last())
            uploadTags(request.POST.get('tags').split(),
                       Project.objects.last())
            return redirect('projects')
        else:
            category = Category.objects.all()
            return render(request, 'projects/add.html', {'new_project': project, 'category': category})
コード例 #3
0
def create_mock_data(email):
    account = Account(username=email, email=email)
    account.save()
    workspace = Workspace(account=account)
    workspace.save()
    project1 = Project(title='Project 1',
                       description='Project1 description',
                       workspace=workspace,
                       color='#ffffff')
    project1.save()
    task1 = Task(title='task 1',
                 description='task 1 description',
                 project=project1,
                 estimated_hours=1,
                 status='OPEN',
                 workspace=workspace,
                 assigned_user=account)
    task1.save()
    task2 = Task(title='task 2',
                 description='task 2 description',
                 project=project1,
                 estimated_hours=1,
                 status='READY',
                 workspace=workspace,
                 assigned_user=account)
    task2.save()
    project2 = Project(title='Project 2',
                       description='Project2 description',
                       workspace=workspace,
                       color='#ffff00')
    project2.save()
    task3 = Task(title='task 3',
                 description='task 3 description',
                 project=project2,
                 estimated_hours=1,
                 status='IN_PROGRESS',
                 workspace=workspace,
                 assigned_user=account)
    task3.save()
    task4 = Task(title='task 4',
                 description='task 4 description',
                 project=project2,
                 estimated_hours=1,
                 status='DONE',
                 workspace=workspace,
                 assigned_user=account)
    task4.save()
    tasks = Task.objects.all()
    cycle = Cycle(goal_title='Default',
                  start_date=timezone.now(),
                  workspace=workspace)
    cycle.save()
    activeCycle = Cycle(goal_title='Active',
                        start_date=timezone.now(),
                        end_date=timezone.now() + timezone.timedelta(7),
                        workspace=workspace)
    activeCycle.save()
    activeCycle.tasks.set(tasks)
    cycle.save()
コード例 #4
0
 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()
コード例 #5
0
ファイル: tests.py プロジェクト: isabella232/tock
    def setUp(self):
        agency = Agency(name='General Services Administration')
        agency.save()
        self.user = User.objects.create(username='******',
                                        first_name='aaron',
                                        last_name='snow')
        self.billable_accounting_code = AccountingCode(code='abc',
                                                       agency=agency,
                                                       office='18F',
                                                       billable=True)
        self.billable_accounting_code.save()

        self.non_billable_accounting_code = AccountingCode(code='def',
                                                           agency=agency,
                                                           office='18F',
                                                           billable=False)
        self.non_billable_accounting_code.save()

        self.organization = Organization(name='test-org',
                                         active=True,
                                         description='a test org')
        self.organization.save()

        self.profit_loss_account = ProfitLossAccount(
            name='PIF',
            accounting_string='This_is_a_string',
            as_start_date=datetime.date(2016, 10, 1),
            as_end_date=datetime.date(2017, 9, 30))
        self.profit_loss_account.save()

        self.project = Project(accounting_code=self.billable_accounting_code,
                               profit_loss_account=self.profit_loss_account,
                               name='Test Project',
                               start_date='2016-01-01',
                               end_date='2016-02-01',
                               agreement_URL='https://thisisaurl.com',
                               project_lead=self.user)
        self.project.save()

        self.project_no_url = Project(
            accounting_code=self.billable_accounting_code,
            name='Test_no_url Project',
            start_date='2016-02-01',
            end_date='2016-02-02',
            agreement_URL='',
            project_lead=self.user)
        self.project_no_url.save()

        self.project_no_lead = Project(
            accounting_code=self.billable_accounting_code,
            name='Test_no_url Project',
            start_date='2016-02-01',
            end_date='2016-02-02',
            agreement_URL='https://thisisaurl.com',
            project_lead=None)
        self.project_no_lead.save()
        self.app.set_user(self.user)
コード例 #6
0
    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)
コード例 #7
0
ファイル: test_models.py プロジェクト: pregression/testr
 def setUp(self):
     user = User.objects.create(email="*****@*****.**")
     owner = Owner.objects.create(user_id=user.id)
     active_project = Project(name="foo", owner_id=owner.id)
     inactive_project = Project(name="bar",
                                is_active=False,
                                owner_id=owner.id)
     active_project.save()
     inactive_project.save()
     self.active_project = active_project
     self.inactive_project = inactive_project
コード例 #8
0
ファイル: views.py プロジェクト: ajufrancis/lernanta
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))
コード例 #9
0
ファイル: views.py プロジェクト: v-i-s-h-n-u-ps/fyp_be
 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)
コード例 #10
0
    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)
コード例 #11
0
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})
コード例 #12
0
ファイル: tests.py プロジェクト: cristianlp/bullet-train-api
    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)
コード例 #13
0
    def handle(self, *args, **options):
        count = options.get('count', 1)
        fake = Factory.create('ru_RU')

        users = UserProfile.objects.all()
        languages = ProgrammingLanguage.objects.all()

        for i in range(count):
            self.stdout.write("Adding project %d of %d" % (i + 1, count),
                              self.style.SUCCESS)
            project = Project()
            project.name = fake.company()
            project.slug = fake.slug()
            project.description = fake.paragraph()
            project.owner = random.choice(users).user
            project.start_date = fake.date()
            project.end_date = fake.future_date()
            project.is_active = random.randint(0, 100) > 20
            # git = models.CharField(max_length=100, blank=True, null=True)
            project.uri = fake.url()
            project.programming_language = random.choice(languages)
            project.save()

            print(project.name)
            self.stdout.write("Project %s added" % (project.name, ))
            self.stdout.write("Project %s added" % (project.name, ),
                              self.style.SUCCESS)

        self.stdout.write(self.style.SUCCESS('Success'))
コード例 #14
0
ファイル: tests.py プロジェクト: mkcode/lernanta
    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()
コード例 #15
0
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})
コード例 #16
0
 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.")
コード例 #17
0
ファイル: views.py プロジェクト: rasmunk/projects-site
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)
コード例 #18
0
 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?")
コード例 #19
0
 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...")
コード例 #20
0
 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.")
コード例 #21
0
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)
コード例 #22
0
ファイル: views.py プロジェクト: yongxiangng/DjangoWeb
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)
コード例 #23
0
def make_api_project(project_data):
    from projects.models import Project
    for key in ['users', 'resource_uri', 'absolute_url', 'downloads']:
        if key in project_data:
            del project_data[key]
    project = Project(**project_data)
    return project
コード例 #24
0
ファイル: organization.py プロジェクト: rogue26/processy.io
    def save(self, commit=True):
        if commit:
            self.request.user.organization = self.instance
            self.request.user.save()

            pre_existing_ref_projects = Project.objects.filter(
                is_the_reference_project=True, created_by=self.request.user)

            if not pre_existing_ref_projects.exists():
                ref_project = Project(
                    name="Reference project",
                    description="Placeholder project for holding an "
                    "organization's default workstreams.",
                    is_the_reference_project=True)
                ref_project.save()

                ref_project.organization = self.instance
                ref_project.save()
            else:
                # if a user has a "personal" reference project and they create an organization, that reference project
                # will be associated with the organization. At the moment, processy doesn't allow for both a personal
                # reference project and an organization reference project under the same account. This is probably the
                # correct behavior, but this can be revisited later.
                ref_project = pre_existing_ref_projects.first()
                ref_project.organization = self.instance

        return super().save(commit=commit)
 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')
コード例 #26
0
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')
コード例 #27
0
ファイル: tests.py プロジェクト: vtamara/lernanta
 def test_unique_slugs(self):
     """Test that each project will get a unique slug"""
     project = Project(
         name='My Cool Project',
         short_description='This project is awesome',
         long_description='No really, its good',
     )
     project.save()
     self.assertEqual('my-cool-project', project.slug)
     project2 = Project(
         name='My Cool  Project',
         short_description='This project is awesome',
         long_description='This is all very familiar',
     )
     project2.save()
     self.assertEqual('my-cool-project-2', project2.slug)
コード例 #28
0
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')
コード例 #29
0
ファイル: utils.py プロジェクト: maxnth/ocr2tei-wip
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)
コード例 #30
0
def addProjectDB(request):
    if request.method == 'POST' and request.FILES:
        project = Project()
        project.title = request.POST.get('title')
        project.details = request.POST.get('details')
        category = Category.objects.get(id=request.POST.get('categories'))
        project.category = category
        project.total_target = request.POST.get('total_target')
        project.start_date = request.POST.get('start_date')
        project.end_date = request.POST.get('end_date')
        project.user = request.user
        project.save()

        added_project = Project.objects.latest('id')
        tags = request.POST.getlist("tags[]")
        for tag in tags:
            tag_obj = Tag.objects.get_or_create(tag_name=tag)
            added_tag = Tag.objects.latest('id')
            added_tag.projects.add(Project.objects.get(id=added_project.pk))

        counter = int(request.POST.get('counterImg'))
        for i in range(counter + 1):
            fp = 'photos' + str(i)
            photo = request.FILES['{}'.format(fp)]
            fs = FileSystemStorage()
            filename = fs.save(photo.name, photo)
            photo_obj = Picture()
            photo_obj.project = added_project
            photo_obj.photo = filename
            photo_obj.save()

        return redirect('project_add')