Ejemplo n.º 1
0
def study_selection(request, username, review_name):
    review = Review.objects.get(name=review_name,
                                author__username__iexact=username)
    try:
        active_tab = int(request.GET['source'])
    except Exception as e:
        active_tab = -1

    add_sources = review.sources.count()
    import_articles = review.get_source_articles().count()

    steps_messages = []
    if not add_sources:
        steps_messages.append(
            u'Use the <a href="{0}#sources-section">planning tab</a> to add sources to your review.'
            .format(r('protocol', args=(username, review_name))))
    if not import_articles:
        steps_messages.append(
            u'Import the studies using the <a href="{0}">import studies tab</a>.'
            .format(r('import_studies', args=(username, review_name))))

    finished_all_steps = len(steps_messages) == 0

    return render(
        request, 'conducting/conducting_study_selection.html', {
            'review': review,
            'active_tab': active_tab,
            'steps_messages': steps_messages,
            'finished_all_steps': finished_all_steps
        })
Ejemplo n.º 2
0
def signup(request):
    success_url = r('accounts:login')
    template_name = 'accounts/signup.html'
    user_form = forms.CustomUserCreationForm()
    institution_form = forms.InstitutionForm()

    if request.user.is_authenticated:
        return redirect(r('core:dashboard'))

    if request.method == "POST":
        user_form = forms.CustomUserCreationForm(request.POST)
        institution_form = forms.InstitutionForm(request.POST)

        if institution_form.is_valid() and user_form.is_valid():
            # create institution
            institution = institution_form.save()
            # create admin user
            user_form.cleaned_data['is_admin'] = True
            user = user_form.save()
            user.admin.institution = institution
            user.admin.save()
            return redirect(success_url)

    context = {'institution_form': institution_form, 'user_form': user_form}
    return render(request, template_name, context)
Ejemplo n.º 3
0
def validar_convenio(request):
    if request.method == 'GET':
        return HttpResponseRedirect(r('core:core_index_professor'))
    else:
        id = request.POST.get('convenio_id', '')
        if id != '':
            convenio = ConvenioModel.objects.filter(pk=id)[0]
            context = {'media_url': settings.MEDIA_URL, 'convenio': convenio}
            return render(request, 'validar_convenio.html', context)
        else:
            return HttpResponseRedirect(r('core:core_index_professor'))
Ejemplo n.º 4
0
    def test_a_manager_can_not_checkout_an_order(self, client_w_customer, an_order, a_manager):
        client = client_w_customer

        response = client.post(r('order-update', args=[1]), an_order, follow=True)
        assert 'bob' in str(response.content)
        assert 'Abacate' in str(response.content)

        client.logout()
        assert client.login(username=a_manager.username, password='******')

        response = client.post(r('order-checkout', args=[1]), follow=True)
        assert response.status_code == 403
        assert Order.objects.get(pk=1).status == Order.OrderStatus.OPENED
Ejemplo n.º 5
0
    def test_a_customer_can_not_checkout_another_customer_order(
            self, client, a_customer, add_item, another_customer):
        assert a_customer.orders.first().items.first(
        ).product.name == 'Abacate'

        client.logout()
        client.login(username=another_customer.username, password='******')

        response = client.get(r('index'))
        assert response.status_code == 200
        assert 'joe' in str(response.content)

        response = client.post(r('order-checkout', args=[1]), follow=True)
        assert response.status_code == 403
Ejemplo n.º 6
0
def import_bibtex(request):
    review_id = request.POST['review-id']
    source_id = request.POST['source-id']

    review = Review.objects.get(pk=review_id)
    source = Source.objects.get(pk=source_id)

    bibtex_file = request.FILES['bibtex']

    ext = os.path.splitext(bibtex_file.name)[1]
    valid_extensions = ['.bib', '.bibtex']

    if ext in valid_extensions or bibtex_file.content_type == 'application/x-bibtex':
        parser = BibTexParser()
        parser.customization = convert_to_unicode
        bib_database = bibtexparser.load(bibtex_file, parser=parser)
        articles = bibtex_to_article_object(bib_database, review, source)
        _import_articles(request, source, articles)
    else:
        messages.error(
            request,
            u'Invalid file type. Only .bib or .bibtex files are accepted.')

    return redirect(
        r('import_studies', args=(review.author.username, review.name)))
Ejemplo n.º 7
0
def update_profile(request):
    success_url = r('accounts:profile')
    template_name = 'accounts/profile_form.html'

    if request.user.has_perm('accounts.is_admin'):
        profile = request.user.admin
    elif request.user.has_perm('accounts.is_teacher'):
        profile = request.user.teacher
    elif request.user.has_perm('accounts.is_student'):
        profile = request.user.student

    user_form = forms.CustomUserUpdateForm(request.POST or None,
                                           instance=profile.user)
    profile_form = forms.ProfileForm(request.POST or None, instance=profile)

    if user_form.is_valid() and profile_form.is_valid():
        user_form.save()
        profile_form.save()
        return redirect(success_url)

    context = {
        'form': user_form,
        'profile_form': profile_form,
    }
    return render(request, template_name, context)
Ejemplo n.º 8
0
 def test_a_product_should_not_have_price_lte_zero(self, client_w_manager, register_product, wrong_price):
     new_data = dict(
         price=wrong_price,
     )
     response = client_w_manager.post(r('product-update', args=[1]), new_data, follow=True)
     assert response.status_code == 200
     assert 'Certifique-se que este valor seja maior ou igual a 0.01.' in str(response.content)
Ejemplo n.º 9
0
    def test__upload_file(
        self,
        authorized_client,
    ):
        filename = 'upload_file.csv'
        csv_file = File(open('files/upload_file.csv', 'rb'))

        uploaded_file = SimpleUploadedFile(
            filename,
            csv_file.read(),
            content_type='multipart/form-data',
        )

        url = r('shoes:shoes_import')
        data = {
            'file': uploaded_file,
        }

        headers = {
            'Content-Disposition': 'attachment;filename=upload_file.csv',
        }
        response = authorized_client.post(url, data, headers=headers)
        assert response.status_code == status.HTTP_201_CREATED
        assert Shoes.objects.all().count() == 3
        assert Shoes.objects.all()[0].brand == 'adidas'
Ejemplo n.º 10
0
def move(request):
    move_from_folder_id = request.POST.get('active-folder-id')
    move_from_folder = Folder.objects.get(pk=move_from_folder_id)

    move_to_folder_id = request.POST.get('action-folder-id')
    move_to_folder = Folder.objects.get(pk=move_to_folder_id)

    if request.POST.get('select-all-pages') == 'all':
        documents = move_from_folder.documents.all()
    else:
        document_ids = request.POST.getlist('document')
        documents = Document.objects.filter(id__in=document_ids)

    querystring = request.POST.get('querystring', '')
    documents = get_filtered_documents(documents, querystring)

    move_to_folder.documents.add(*documents)
    move_from_folder.documents.remove(*documents)

    messages.success(
        request,
        u'Documents moved from folder {0} to {1} successfully!'.format(
            move_from_folder.name, move_to_folder.name))
    redirect_to = request.POST.get('redirect', r('library:index'))
    return redirect(redirect_to)
Ejemplo n.º 11
0
 def test_a_customer_can_not_delete_product(self, register_product,
                                            client_w_customer):
     response = client_w_customer.post(r('product-delete', args=[1]),
                                       follow=True)
     assert 'bob' not in str(response.content)
     assert Product.objects.exists()
     assert response.status_code == 403
Ejemplo n.º 12
0
def update_student(request, pk):
    template_title = 'Editar Student'
    template_name = 'accounts/student/student_form.html'

    classes_id = utils.get_classes(request.user)
    student = get_object_or_404(models.Student, pk=pk, class_id__in=classes_id)

    user_form = forms.CustomUserUpdateForm(request.POST or None,
                                           instance=student.user)
    student_form = forms.ProfileForm(request.POST or None, instance=student)

    if user_form.is_valid() and student_form.is_valid():
        user_form.save()
        student_form.save()
        success_url = r('accounts:list-student',
                        kwargs={'class': student.class_id.pk})
        return redirect(success_url)

    context = {
        'form': user_form,
        'class': student.class_id,
        'student_form': student_form,
        'template_title': template_title,
    }
    return render(request, template_name, context)
Ejemplo n.º 13
0
    def test_put_content_not_found(self):

        url = r("content:contents_viewset", args=["test-slug-invalid"])

        response = self.client.put(url, format="json")

        assert response.status_code == status.HTTP_404_NOT_FOUND
Ejemplo n.º 14
0
    def test_forgot(self):
        response = self.client.post(
            r('rest_auth:forgot'),
            data={'email': self.user.email},
        )

        self.assertEqual(response.status_code, 200)
Ejemplo n.º 15
0
def pos_validar_documento_estagio(request):
    if request.method == 'GET':
        return HttpResponseRedirect(r('core:core_index_professor'))
    else:
        id = request.POST.get('documento_id', '')
        if id != '':
            obs_padrao = 'Parecer Emitido pelo docente.'
            observacao = request.POST.get('observacao_professor', obs_padrao)
            aprovado = request.POST.get('aprovado_reprovado', '1')
            documento = DocumentoEstagioModel.objects.filter(pk=id)[0]
            documento.observacao_professor = observacao
            documento.aprovado_professor = aprovado
            documento.save()
            return render(request, 'pos_validar_documento_estagio.html')
        else:
            return HttpResponseRedirect(r('core:core_index_professor'))
Ejemplo n.º 16
0
def pre_validar_convenio(request):
    if request.method == 'GET':
        convenios = ConvenioModel.objects.filter(observacao_professor='')
        context = {'media_url': settings.MEDIA_URL, 'convenios': convenios}
        return render(request, 'pre_validar_convenio.html', context)
    else:
        return HttpResponseRedirect(r('core:core_index_professor'))
Ejemplo n.º 17
0
def update_teacher(request, pk):
    success_url = r('accounts:list-teacher')
    template_title = 'Editar Profesor'
    template_name = 'accounts/teacher/teacher_form.html'

    institution = request.user.admin.institution
    teacher = get_object_or_404(
        models.Teacher,
        pk=pk,
        institution=institution,
    )

    user_form = forms.CustomUserUpdateForm(request.POST or None,
                                           instance=teacher.user)
    teacher_form = forms.ProfileForm(request.POST or None, instance=teacher)

    if user_form.is_valid() and teacher_form.is_valid():
        user_form.save()
        teacher_form.save()
        return redirect(success_url)

    context = {
        'form': user_form,
        'teacher_form': teacher_form,
        'template_title': template_title,
    }
    return render(request, template_name, context)
Ejemplo n.º 18
0
def delete_documents(request):
    select_all_pages = request.POST.get('select-all-pages')
    document_ids = request.POST.getlist('document')
    folder_id = request.POST.get('active-folder-id')

    if folder_id:
        folder = Folder.objects.get(pk=folder_id)
        if select_all_pages == 'all':
            documents = folder.documents.all()
        else:
            documents = folder.documents.filter(id__in=document_ids)
    else:
        if select_all_pages == 'all':
            documents = Document.objects.filter(user=request.user)
        else:
            documents = Document.objects.filter(user=request.user,
                                                id__in=document_ids)

    querystring = request.POST.get('querystring', '')
    documents = get_filtered_documents(documents, querystring)

    documents_size = documents.count()
    documents.delete()
    messages.success(
        request, u'{0} {1} successfully deleted!'.format(
            documents_size, get_document_verbose_name(documents_size)))
    redirect_to = request.POST.get('redirect', r('library:index'))
    return redirect(redirect_to)
Ejemplo n.º 19
0
class UpdateContentView(base_views.ContentBaseQueryset,
                        base_core_views.BaseFormView, generic.UpdateView):
    form_class = forms.ContentForm
    success_url = r('content:list-content')
    template_title = 'Editar Conteúdo'
    template_name = 'content/content_form.html'
    context_object_name = 'content'
Ejemplo n.º 20
0
    def test_get_content_not_found(self):

        url = r("content:contents_viewset", args=[10])

        response = self.client.get(url, format="json")

        assert response.status_code == status.HTTP_404_NOT_FOUND
Ejemplo n.º 21
0
 def result_expected(self, data):
     resp = self.client.post(r('core:conserto_list'), data)
     self.assertContains(resp, '<td>CCE</td>')
     self.assertContains(resp, '<td>HPS-2071</td>')
     self.assertContains(resp, '<td>NÃO LIGA</td>')
     self.assertNotContains(resp, '<td>PHILCO</td>')
     self.assertNotContains(resp, '<td>PC-1416</td>')
     self.assertNotContains(resp, '<td>FONTE ALTA</td>')
Ejemplo n.º 22
0
 def test_invalid_token(self):
     user = UserModel.objects.create(username='******')
     uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
     self.client.get(
         r('rest_auth:verify_email_confirm',
           kwargs=dict(uidb64=uidb64, token='efgh-ijkl')),
         follow=True,
     )
Ejemplo n.º 23
0
def services_url_month(slug):
    date = timezone.now()
    return r('services:month',
             args=(
                 slug,
                 date.year,
                 str(date.month).zfill(2),
             ))
Ejemplo n.º 24
0
def convenio_por_empresa(request):
    if request.method == 'GET':
        id_user = request.user.pk
        convenios = ConvenioModel.objects.filter(empresa_id=id_user)
        context = {'media_url': settings.MEDIA_URL, 'convenios': convenios}
        return render(request, 'convenio_por_empresa.html', context)
    else:
        return HttpResponseRedirect(r('core:core_index_empresa'))
 def result_expected(self, data):
     resp = self.client.post(r('core:conserto_list'), data)
     self.assertContains(resp, '<td>CCE</td>')
     self.assertContains(resp, '<td>HPS-2071</td>')
     self.assertContains(resp, '<td>NÃO LIGA</td>')
     self.assertNotContains(resp, '<td>PHILCO</td>')
     self.assertNotContains(resp, '<td>PC-1416</td>')
     self.assertNotContains(resp, '<td>FONTE ALTA</td>')
Ejemplo n.º 26
0
 def test_invalid_session(self):
     user = UserModel.objects.create(username='******')
     uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
     self.client.get(
         r('rest_auth:verify_email_confirm',
           kwargs=dict(uidb64=uidb64,
                       token=EmailVerificationConfirmView.
                       INTERNAL_VERIFY_URL_TOKEN)))
Ejemplo n.º 27
0
def register_product(client_w_manager):
    data = dict(
        name='Abacate',
        price=0.01,
        is_active=True,
    )
    response = client_w_manager.post(r('product-create'), data, follow=True)
    return response
Ejemplo n.º 28
0
def upload_file(request):
    if request.method == 'POST':
        order_form = OrderForm(request.POST, request.FILES)
        if order_form.is_valid():
            latitude = request.POST['latitude']
            longitude = request.POST['longitude']

            uploaded_file = request.FILES['file'].temporary_file_path()
            uploaded_filename = request.FILES['file'].name

            if check_uploaded_file(request.FILES['file']):
                f_list = drive.ListFile({
                    'q':
                    "'root' in parents and trashed=false"
                }).GetList()
                folder_id = None
                for f in f_list:
                    if f['title'] == 'shapefiles':
                        folder_id = f['id']

                file = drive.CreateFile({
                    'parents': [{
                        'kind': "drive#fileLink",
                        'id': folder_id
                    }],
                    'title':
                    uploaded_filename
                })

                file.SetContentFile(uploaded_file)
                file.Upload()

                shapefile = Shapefile.objects.create(key=file['id'])

                coordinates = Coordinates.objects.create(
                    title=request.POST['title'],
                    latitude=request.POST['latitude'],
                    longitude=request.POST['longitude'],
                    shapefile=shapefile)

                order = ScrapingOrder.objects.create(
                    coordinates=coordinates, raster=Raster.objects.create())

                order = serializers.serialize("json", [order])
                crawl_order.delay(order)

                messages.success(
                    request, 'The order {} added successfull.'.format(
                        request.POST['title']))
                return HttpResponseRedirect(r('core:orders'))
        else:
            context = {'form': order_form}
            return render(request, 'core/new_order.html', context)
    else:
        order_form = OrderForm()

    context = {'form': order_form}
    return render(request, 'core/new_order.html', context)
Ejemplo n.º 29
0
class UpdateAddressView(base_core_views.BaseFormView, generic.UpdateView):
    form_class = forms.AddressForm
    success_url = r('accounts:profile')
    template_title = 'Editar Endereço'
    template_name = 'accounts/address/address_form.html'

    def get_queryset(self):
        addresses = self.request.user.addresses.all()
        return addresses
Ejemplo n.º 30
0
    def test__create_new_shoes_with_invalid_payload(self, authorized_client,
                                                    shoes_payload_invalid):

        url = r('shoes:shoes')

        payload = shoes_payload_invalid

        response = authorized_client.post(url, data=payload, format='json')
        assert response.status_code == status.HTTP_400_BAD_REQUEST
Ejemplo n.º 31
0
    def test_create_content_with_invalid_payload(self,
                                                 content_invalid_payload):

        url = r("content:contents")

        payload = content_invalid_payload

        response = self.client.post(url, data=payload, format="json")
        assert response.status_code == status.HTTP_400_BAD_REQUEST
Ejemplo n.º 32
0
 def get_absolute_url(self):
     return r('core:conserto_detail', kwargs={'pk': self.pk})
 def setUp(self):
     mommy.make('core.Conserto', 30)
     self.resp = self.client.post(r('core:conserto_list'))
 def setUp(self):
     self.resp = self.client.get(r('core:search_repair'))
 def setUp(self):
     modelo = mommy.make('core.Modelo', marca__descricao=u'CCE', descricao='HPS-2071')
     conserto = mommy.make('core.Conserto', modelo=modelo, defeito__descricao=u'NÃO LIGA')
     mommy.make('core.Solucao', conserto=conserto, solucao=u'Ver capacitor C1', _quantity=2)
     conserto.solucao_set.create()
     self.resp = self.client.get(r('core:conserto_detail', kwargs={'pk': conserto.pk}))