def test_create_article(self): url = reverse_lazy('auth_app:api_login') data = { 'email': settings.SUPERUSER_EMAIL, 'password': settings.SUPERUSER_PASSWORD, } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK, response.data) # self.client.force_login() if self.user.is_authenticated: url = reverse_lazy('blog:post-list') data = { 'title': 'Sport', 'category': self.category.id, 'content': 'Test content', } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data) print(response.data) url = reverse_lazy('blog:post-list') data = { 'title': 'Sport', 'category': self.category.id, 'content': 'Test content', } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.data) print(response.data)
def basic_upload_view(request): if request.method == 'POST': form = BasicUploadForm(request.POST, request.FILES) if form.is_valid(): apk = request.FILES['apk'] if apk.size > settings.MAX_APK_UPLOAD_SIZE: messages.warning(request, 'Submitted file is too large.') return redirect(reverse_lazy('front:home')) with NamedTemporaryFile() as tmp: for chunk in apk.chunks(): tmp.write(chunk) tmp.seek(0) if is_android(tmp.name) != 'APK': messages.warning(request, 'Submitted file is not a valid APK.') return redirect(reverse_lazy('front:home')) sha256 = get_sha256_of_file(tmp) if default_storage.exists(sha256): # analyze(sha256, force=True) return redirect(reverse_lazy('front:report', [sha256])) else: default_storage.save(sha256, tmp) analyze(sha256) return redirect(reverse_lazy('front:report', [sha256])) return redirect(reverse_lazy('front:home'))
class AllModelFieldsMetadata(MetaData): model = wf_models.AllModelFields update_fields = { 'f_file': { # ensure upload_url is lazy (premature import case) 'upload_url': format_lazy('{}{}', 'http://localhost:8000', reverse_lazy('all-model-fieldss-accept-file')) }, 'f_photo': { # ensure upload_url is lazy (premature import case) 'upload_url': format_lazy('{}{}', 'http://localhost:8000', reverse_lazy('all-model-fieldss-accept-file')) } } def get_f_fk_rel_dataset_url(self, field, obj): return 'http://localhost:8000%s' % reverse_lazy('books-list') def get_f_m2m_rel_dataset_url(self, field, obj): return 'http://localhost:8000%s' % reverse_lazy('authors-list') def get_title(self, request, view, obj: wf_models.AllModelFields): if obj: return _('Edit AllModelFields "{0}"').format(obj.printable_name) return _('Create AllModelFields')
def test_password_reset(self): url = reverse_lazy('auth_app:api_forgot_password') data = {'email': self.user.email} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK, response.data) print(response.data) self.assertEqual(len(mail.outbox), 1) # print('mail', mail.outbox[0]) # print(mail.outbox[0].message()) url_conf = reverse_lazy('auth_app:api_password_reset_confirm') string = str(mail.outbox[0].message()) pattern = r'(http?://[^\"\s]+)' result = re.findall(pattern, string) activate = result[0] activate = activate.split('/') # print(activate) data = { "new_password1": "string1986", "new_password2": "string1986", "uid": activate[5], "token": activate[6], } # print(activate[5], activate[6]) response = self.client.post(url_conf, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK, response.data) print(response.data)
def test_get_profile(self): url = reverse_lazy('auth_app:api_login') data = { 'email': settings.SUPERUSER_EMAIL, 'password': settings.SUPERUSER_PASSWORD, } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK, response.data) url = reverse_lazy('profiles:profile_detail') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) url = reverse_lazy('profiles:profile_detail') data = { 'first_name': 'admin2', 'last_name': 'AA2', 'mobile': '+79066669999', 'location': 'london', } response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK, response.data) print(response.data)
def get_links(self, obj): request = self.context['request'] username = obj.get_username() return { 'self': reverse_lazy('user-detail', kwargs = {User.USERNAME_FIELD: username}, request=request), 'tasks': '{}?assigned={}'.format(reverse_lazy('task-list', request=request), username) }
def my_rule_edit_view(request, uuid): if not request.user.is_authenticated: return redirect(reverse_lazy('front:home')) if request.method == 'GET': rule = Yara.objects.get(id=uuid) new_rule = YaraCreateForm(instance=rule) return render(request, 'front/yara_rules/my_rule_edit.html', { 'form': new_rule, 'edit': True }) elif request.method == 'POST': rule = Yara.objects.get(id=uuid) new_rule = YaraCreateForm(request.POST or None, instance=rule) try: new_rule = new_rule.save(commit=False) new_rule.owner = request.user new_rule.last_update = timezone.now() new_rule.save() delete_es_matches(request, rule) messages.success(request, 'Your rule has been updated!') except Exception: return render(request, 'front/yara_rules/my_rule_edit.html', {'form': new_rule}) return redirect(reverse_lazy('front:my_rules')) else: return HttpResponseBadRequest()
def get(self, request, *args, **kwargs): if 'sha256' not in kwargs: return redirect(reverse_lazy('front:home')) sha = kwargs['sha256'] cache_key = f'html_report_{sha}' # First, check if the report is already in cache cached_report = cache.get(cache_key) if cached_report: return cached_report # Not cached so, let's compute the report es = Elasticsearch([settings.ELASTICSEARCH_HOST]) try: result = es.get(index=settings.ELASTICSEARCH_APK_INDEX, id=sha)['_source'] if 'analysis_date' not in result: messages.info( request, 'The analysis is still running, refresh this page in few minutes.' ) return render(request, 'front/report.html', {'result': result}) else: # The analysis is done so put the report into the cache html_report = render(request, 'front/report.html', {'result': result}) cache.set(cache_key, html_report) return html_report except Exception: return redirect(reverse_lazy('front:home'))
def get_links(self, obj): return { "self": utils.get_resource_path(obj), "feed": reverse_lazy("user-feed", kwargs={"pk": obj.id, "format": settings.API_FORMAT}), "timeline": reverse_lazy("user-timeline", kwargs={"pk": obj.id, "format": settings.API_FORMAT}), "following": reverse_lazy("user-following", kwargs={"pk": obj.id, "format": settings.API_FORMAT}), "followers": reverse_lazy("user-followers", kwargs={"pk": obj.id, "format": settings.API_FORMAT}), }
def api_root(request, format=None): return Response({ 'courses': reverse_lazy('course:course-list', request=request, format=format), #'reviews': reverse('course:review-list', request=request, format=format), 'users': reverse_lazy('course:user-list', request=request, format=format) })
def api_root(request, format=None): return Response({ 'services': reverse_lazy('api:service-list', request=request, format=format), 'organizations': reverse_lazy('api:organization-list', request=request, format=format), 'testimonials': reverse_lazy('api:testimonials_list', request=request, format=format) })
def get(self, request): data = { 'list-comitees': reverse_lazy('api-events:com-list', request=request), 'list-events': reverse_lazy('api-events:event-list', request=request), 'list-athletes': reverse_lazy('api-events:athlete-list', request=request), } return Response(data)
def get(self, request): links = { 'teams': reverse_lazy('team-list', request=request), 'users': { 'all': reverse_lazy('user-list', request=request), 'organizers': reverse_lazy('user-list-organizers', request=request), 'attendees': reverse_lazy('user-list-attendees', request=request), }, 'event': reverse_lazy('event-detail', request=request), } return Response(links)
def _resolve_command_binary(self, request, node_id, command): urls = dict() cid = command['id'] on = command['values']['on'] off = command['values']['off'] urls['on'] = reverse_lazy('commands-set', kwargs={ 'pk': node_id, 'cid': cid, 'value': on }, request=request) urls['off'] = reverse_lazy('commands-set', kwargs={ 'pk': node_id, 'cid': cid , 'value': off }, request=request) urls['current'] = reverse_lazy('commands-get', kwargs={ 'pk': node_id, 'cid': cid }, request=request) command['urls'] = urls
def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): if APIClient().add_products(form): self.success_url = reverse_lazy('formset_default_success', kwargs={'success': 1}) else: self.success_url = reverse_lazy('formset_default_success', kwargs={'success': 2}) return self.form_valid(form) else: return self.form_invalid(form) return super(DefaultFormsetView, self).post(request, *args, **kwargs)
def _get_app_url(self, request, region, app_type): routes = { US: { INDIVIDUAL: reverse_lazy('wfrs-api-apply-us-individual', request=request), JOINT: reverse_lazy('wfrs-api-apply-us-join', request=request), }, CA: { INDIVIDUAL: reverse_lazy('wfrs-api-apply-ca-individual', request=request), JOINT: reverse_lazy('wfrs-api-apply-ca-joint', request=request), }, } return routes.get(region, {}).get(app_type)
def get_links(self, obj): request = self.context['request'] username = obj.get_username() return { 'self': reverse_lazy('user-detail', kwargs={User.USERNAME_FIELD: username}, request=request), 'tasks': '{}?assigned={}'.format(reverse_lazy('task-list', request=request), username) }
def test_create_article_forbidden(self): url = reverse_lazy('auth_app:logout') response = self.client.post(url) self.assertEqual(response.status_code, status.HTTP_200_OK) url = reverse_lazy('blog:post-list') data = { 'title': 'Sport', 'category': self.category.id, 'content': 'Test content', } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) print("Create article forbidden", response.data)
def generate(self, request): if request.method == 'GET': return Response({}, status=status.HTTP_200_OK) if not hasattr(request.user, 'creator'): return Response({'detail': 'you are not a creator'}, status=status.HTTP_403_FORBIDDEN) creator = request.user.creator class_name = request.data['class_name'] clicker_class = models.ClickerClass.objects.get(class_name=class_name) # class_size = clicker_class.get_connected_devices() # if class_size == 0: # return Response({'detail': 'class size is zero'}, status=status.HTTP_403_FORBIDDEN) interaction_type = models.InteractionType.objects.get(slug_name='regression') for m in models.Interaction.objects.filter(clicker_class=clicker_class): m.state = models.Interaction.COMPLETE m.save() # create game of life instance and corresponding interaction interaction = models.Interaction.objects.create(clicker_class=clicker_class, state=models.Interaction.ACTIVE, creator=creator, interaction_type=interaction_type) interaction.save() regression = models.Regression(interaction=interaction, x_label="Height (cm)", y_label="Weight (kg)") regression.save() interaction_data = { 'assignments': {}, 'urls': { 'source': str(reverse_lazy('regression-detail', args=[regression.id])), 'plot_items': str(reverse_lazy('regressionplotitem-list')) }, 'interaction': interaction.id, 'instance_script': '/static/js/:type:/regression.bundle.js', 'instance_component_name': 'Regression' } interaction.data_json = json.dumps(interaction_data) interaction.save() return Response(serializers.RegressionSerializer(regression, context={'request': request}).data, status=status.HTTP_201_CREATED)
def get_links(self, obj): request = self.context['request'] links = { 'self': reverse_lazy('task-detail', kwargs={'pk': obj.pk}, request=request), 'sprint': None, 'assigned': None } if obj.sprint_id: links['sprint'] = reverse_lazy('sprint-detail', kwargs={'pk':obj.sprint_id}, request=request) if obj.assigned: links['assigned'] = reverse_lazy('user-detail', kwargs={User.USERNAME_FIELD: obj.assigned}, request=request) return links
def download_sample_view(request, sha256): if not request.user.is_authenticated: return redirect(reverse_lazy('front:home')) if request.method == 'GET': if not default_storage.exists(sha256): return redirect(reverse_lazy('front:home')) response = HttpResponse( default_storage.open(sha256).read(), content_type="application/vnd.android.package-archive") response[ 'Content-Disposition'] = f'inline; filename=pithus_sample_{sha256}.apk' return response
def my_rule_delete_view(request, uuid=None): if not request.user.is_authenticated: return redirect(reverse_lazy('front:home')) if request.method == 'GET': rule = Yara.objects.get(id=uuid) try: delete_es_matches(request, rule) rule.delete() messages.success(request, 'Your rule has been deleted.') return redirect(reverse_lazy('front:my_rules')) except Exception as e: logging.exception(e) return redirect(reverse_lazy('front:my_rules'))
def get(self, request, *args, **kwargs): raw_match_string = self.request.query_params.get('match', '') match_string = ultils.translate_raw_match_string(raw_match_string) if not match_string: job_list = self.job_queryset.get_all_jobs() else: job_list = self.job_queryset.search(match_string=match_string) if not job_list: return Response(status=status.HTTP_200_OK, data={ 'list': None, 'count': 0, 'next_page': None }) page = ultils.convert_int_or_set_default( self.request.query_params.get('p'), default=1) num = ultils.convert_int_or_set_default( num=self.request.query_params.get('n'), default=10) reviews, next_page = ultils.get_data_and_next_page(data=job_list, num=num, page=page) if next_page: if not match_string: append_string = urllib.urlencode({'p': next_page, 'n': num}) next_page = '{0}?{1}'.format( reverse_lazy('jobsite_job_list', request=request), append_string) else: append_string = urllib.urlencode({ 'match': raw_match_string, 'p': next_page, 'n': num }) next_page = '{0}?{1}'.format( reverse_lazy('jobsite_job_search', request=request), append_string) reviews = JobListSerializer(reviews, many=True) data = { 'list': reviews.data, 'count': len(reviews.data), 'next_page': next_page } return Response( status=status.HTTP_200_OK, data=data, )
def test_article_list(self): url = reverse_lazy('blog:post-list', ) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK, response.data) print(response.data) self.assertEqual(response.data.get('count'), 1)
def test_copy_draft_standard_temporary_application_successful(self): """ Ensure we can copy a standard temporary application that is a draft """ self.original_application = self.create_draft_standard_application( self.organisation) self.original_application.export_type = ApplicationExportType.TEMPORARY self.original_application.temp_export_details = "temporary export details" self.original_application.is_temp_direct_control = True self.original_application.proposed_return_date = "2025-05-11" self.submit_application(self.original_application) self.url = reverse_lazy("applications:copy", kwargs={"pk": self.original_application.id}) self.data = { "name": "New application", "have_you_been_informed": ApplicationExportLicenceOfficialType.YES, "reference_number_on_information_form": "54321-12", } self.response = self.client.post(self.url, self.data, **self.exporter_headers) self.response_data = self.response.json()["data"] self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) self.assertNotEqual(self.response_data, self.original_application.id) self.copied_application = StandardApplication.objects.get( id=self.response_data) self._validate_standard_application()
class SignUpApiViewTests(TestCase): url = reverse_lazy('register-list') def setUp(self): self.client = APIClient() def test_should_create_user(self): FOO_EMAIL = '*****@*****.**' payload = { 'email': FOO_EMAIL, 'password': '******', } self.client.post(self.url, payload) self.assertTrue( get_user_model().objects.filter(email=FOO_EMAIL).exists()) @skip('send email after API register') def test_should_send_email_with_confirmation_link(self): payload = { 'email': '*****@*****.**', 'password': '******', } self.client.post(self.url, payload) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Confirm your email')
def _resolve_url(self, request, wtf, container): assert container association = container['association'] for item in container['items']: item['url'] = reverse_lazy('mixes-details', kwargs={ 'pk': item['identifier'], 'wtf': wtf, 'entry': association['entry'] }, request=request)
class ListingView(FormMixin, DetailView): #template_name = 'listing/listing.html' template_name = 'feather/listing_detail.html' model = Listing form_class = ListingContactForm success_url = reverse_lazy('thank-you') def get_queryset(self): if self.request.user.is_staff: return Listing.objects.all() return Listing.objects.active() def get_context_data(self, **kwargs): context = super(ListingView, self).get_context_data(**kwargs) form_class = self.get_form_class() context['form'] = self.get_form(form_class) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.send_contact_form(self.object) return super(ListingView, self).form_valid(form)
def test_question_random_list(self): """SHOULD get random list of questions with default limit = 5""" response = self.client.get(reverse_lazy("questions-random-list")) response_count = len(response.data) assert response.status_code == status.HTTP_200_OK assert response_count == 5
def require_admin_approval(sender, **kwargs): # make user inactive by default user = kwargs['email_address'].user user.is_active = False user.save() activation_link = reverse_lazy('account-activate', args=[kwargs['email_address']], request=kwargs['request']) admins = User.objects.filter(is_superuser=True) msg = EmailMultiAlternatives( 'MIQA Account Approval - New User', f'A new user with the email {kwargs["email_address"]} has created ' 'an account in MIQA. As an administrative user, it is your responsibility ' 'to activate this account if you believe this user is legitimate. ' 'If you believe this account should not be activated, reach out to this user' f'{" and other administrators." if len(admins) > 1 else "."} ' '\n\n ' f'To activate this account, visit {activation_link} ' '\n\n ' 'Thank you for using MIQA! ', settings.DEFAULT_FROM_EMAIL, [admin.email for admin in admins], ) msg.send()
def get_context_data(self, **kwargs): context = super(ItemDetail, self).get_context_data(**kwargs) ts_item = {'ts_api_root': str(reverse_lazy('api-root', request=self.request)), 'ts_item_uuid': self.get_object().uuid } context['ts_item'] = json.dumps(ts_item) return context
def create(self, request, *args, **kwargs): ''' Override the create funtion in order to to return to the url list and check url valid ''' url = request.POST["site_link"] if not urllib.parse.urlparse(url).scheme: url = 'http://' + url try: urllib.request.urlopen(url) super(ListCreateBookmarkViewSet, self).create(request, *args, **kwargs) except IntegrityError: messages.info(request, 'This URL all ready exist!') except ValidationError as error: messages.info(request, 'This TITLE all ready exist!') except urllib.error.URLError: messages.info( request, request.POST["site_link"] + ' is not a working link NOT ADDED TO THE LIST!') return HttpResponseRedirect( redirect_to=reverse_lazy('appBookmarks:bookmarks-list'))
def get(self, request, *args, **kwargs): page = ultils.convert_int_or_set_default( self.request.query_params.get('p'), default=None) if page: num = ultils.convert_int_or_set_default( num=self.request.query_params.get('n'), default=10) job_list = self.job_queryset.get_all_jobs() jobs, next_page = ultils.get_data_and_next_page(data=job_list, num=num, page=page) if next_page: next_page = '{0}?p={1}&n={2}'.format( reverse_lazy('jobsite_job_list', request=request), next_page, num) else: jobs = self.job_queryset.get_job_list() next_page = None if jobs: jobs = JobListSerializer(jobs, many=True) data = { 'data': jobs.data, 'count': len(jobs.data), 'next_page': next_page } return Response( status=status.HTTP_200_OK, data=data, ) return Response( status=status.HTTP_404_NOT_FOUND, data='Job not found', )
def test_copy_draft_standard_trade_control_application_successful(self): """ Ensure we can copy a standard trade control application that is a draft """ self.original_application = self.create_draft_standard_application( self.organisation) self.original_application.trade_control_activity = TradeControlActivity.OTHER self.original_application.trade_control_activity_other = "other activity" self.original_application.trade_control_product_categories = [ key for key, _ in TradeControlProductCategory.choices ] self.original_application.save() self.url = reverse_lazy("applications:copy", kwargs={"pk": self.original_application.id}) self.data = { "name": "New application", "have_you_been_informed": ApplicationExportLicenceOfficialType.YES, "reference_number_on_information_form": "54321-12", } self.response = self.client.post(self.url, self.data, **self.exporter_headers) self.response_data = self.response.json()["data"] self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) self.assertNotEqual(self.response_data, self.original_application.id) self.copied_application = StandardApplication.objects.get( id=self.response_data) self._validate_standard_application()
def report(self, request, pk=None): user = request.user emails = settings.REPORT_MAILS url = reverse_lazy('admin:wp_core_question_change', args=([pk]), request=request) question = self.get_object() reason = request.data.get('reason', 'nichts angegeben') params = { 'question': question.text, 'link': url, 'reason': reason, 'reporter': user, } plain = render_to_string('wp_core/mails/report_question_email.txt', params) html = render_to_string('wp_core/mails/report_question_email.html', params) if settings.REPORT_MAILS_ACTIVE: send_mail('Eine Frage wurde gemeldet', plain, '*****@*****.**', emails, html_message=html) slack_notify_report(question.text, reason, url, user) return Response({'success': True})
def test_copy_draft_standard_application_successful(self): """ Ensure we can copy a standard application that is a draft """ self.original_application = self.create_draft_standard_application( self.organisation) self.url = reverse_lazy("applications:copy", kwargs={"pk": self.original_application.id}) self.data = { "name": "New application", "have_you_been_informed": ApplicationExportLicenceOfficialType.YES, "reference_number_on_information_form": "54321-12", } self.response = self.client.post(self.url, self.data, **self.exporter_headers) self.response_data = self.response.json()["data"] self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) self.assertNotEqual(self.response_data, self.original_application.id) self.copied_application = StandardApplication.objects.get( id=self.response_data) self._validate_standard_application()
def test_copy_submitted_open_temporary_application_successful(self): """ Ensure we can copy an open temporary application that is submitted (ongoing or otherwise) """ self.original_application = self.create_draft_open_application( self.organisation) self.original_application.export_type = ApplicationExportType.TEMPORARY self.original_application.temp_export_details = "temporary export details" self.original_application.is_temp_direct_control = True self.original_application.proposed_return_date = "2025-05-11" coa = CountryOnApplication.objects.get( application=self.original_application, country_id="FR") coa.contract_types = ["navy", "army"] coa.save() self.submit_application(self.original_application) self.url = reverse_lazy("applications:copy", kwargs={"pk": self.original_application.id}) self.data = {"name": "New application"} self.response = self.client.post(self.url, self.data, **self.exporter_headers) self.response_data = self.response.json()["data"] self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) self.assertNotEqual(self.response_data, self.original_application.id) self.copied_application = OpenApplication.objects.get( id=self.response_data) self._validate_open_application()
def test_copy_draft_open_trade_control_application_successful(self): """ Ensure we can copy an open application that is a draft """ self.original_application = self.create_draft_open_application( self.organisation, case_type_id=CaseTypeEnum.OICL.id) self.original_application.trade_control_activity = TradeControlActivity.OTHER self.original_application.trade_control_activity_other = "other activity" self.original_application.trade_control_product_categories = [ key for key, _ in TradeControlProductCategory.choices ] self.original_application.save() self.url = reverse_lazy("applications:copy", kwargs={"pk": self.original_application.id}) self.data = {"name": "New application"} self.response = self.client.post(self.url, self.data, **self.exporter_headers) self.response_data = self.response.json()["data"] self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) self.assertNotEqual(self.response_data, self.original_application.id) self.copied_application = OpenApplication.objects.get( id=self.response_data) self._validate_open_application()
def get_url_blog(self, instance): # Se GUARDA la URL de DETALLE de un BLOG asociada a los DISTINTOS Usuarios. url = reverse_lazy('blog_detail_page', kwargs={'user_name': instance.username}) # Se devuelve un string informando de la URL del Blog y a quien pertenece return 'El Blog de %s %s | URL: localhost:8000%s' % ( instance.first_name, instance.last_name, url)
def cadastrar_funcionario(request): if request.method == 'POST': funcionario_form = FuncionarioForm(request.POST, request.FILES) if funcionario_form.is_valid(): funcionario_form.save() return redirect(reverse_lazy('cadastrar_funcionario')) else: funcionario_form = FuncionarioForm() return render(request, 'funcionarios/cadastrar_funcionario.html', {'funcionario_form': funcionario_form})
def cadastrar_conta_receber(request): if request.method == 'POST': conta_receber_form = Conta_receberForm(request.POST) if conta_receber_form.is_valid(): conta_receber_form.save() return redirect(reverse_lazy('cadastrar_conta_receber')) else: conta_receber_form = Conta_receberForm() return render(request, 'conta_receber/cadastrar_conta_receber.html', {'conta_receber_form': conta_receber_form})
def cadastrar_cliente(request): if request.method == 'POST': cliente_form = ClienteForm(request.POST, request.FILES) if cliente_form.is_valid(): cliente_form.save() return redirect(reverse_lazy('cadastrar_cliente')) else: cliente_form = ClienteForm() return render(request, 'clientes/cadastrar_cliente.html', {'cliente_form': cliente_form})
def cadastrar_fornecedor(request): if request.method == 'POST': fornecedor_form = FornecedorForm(request.POST) if fornecedor_form.is_valid(): fornecedor_form.save() return redirect(reverse_lazy('cadastrar_fornecedor')) else: fornecedor_form = FornecedorForm() return render(request, 'fornecedores/cadastrar_fornecedor.html', {'fornecedor_form': fornecedor_form})
def get_task_urls(self, obj): """ retuns end point for different operations tasks. :param obj: task obj :return: dict with url points """ kwargs={'pk': obj.id} url_names = ['task-manage-note', 'task-move-to-folder', 'task-manage-tags', 'task-notes', 'task-toggle-done'] urls = {} for url_name in url_names: urls[url_name.replace('task-', '')]=reverse_lazy(url_name, [obj.id]) if obj.task_set.count(): urls['sub-tasks']=reverse_lazy('task-sub-tasks', [obj.id]) return urls
def cadastrar_mercadoria(request): if request.method == 'POST': mercadoria_form = MercadoriaForm(request.POST) if mercadoria_form.is_valid(): mercadoria_form.save() return redirect(reverse_lazy('cadastrar_mercadoria')) else: mercadoria_form = MercadoriaForm() return render(request, 'mercadorias/cadastrar_mercadoria.html', {'mercadoria_form': mercadoria_form})
def cadastrar_compra(request): if request.method == 'POST': compra_form = CompraForm(request.POST) if compra_form.is_valid(): compra_form.save() return redirect(reverse_lazy('cadastrar_compra')) else: compra_form = CompraForm() return render(request, 'compras/cadastrar_compra.html', {'compra_form': compra_form})
def get_project_detail(self, obj): """Returns URI for object into the project_detail field""" request = self.context['request'] return { 'self': reverse_lazy( 'portfolio_project_detail', kwargs={'slug': obj.slug}, request=request, ) }
def new_bubble_sort_swap(sender, instance, **kwargs): class_name = instance.bubble_sort.interaction.clicker_class.class_name channel = 'bubblesort.{}.client'.format(class_name) url = reverse_lazy('bubblesort-detail', args=[instance.bubble_sort_id]) print "Publishing to redis:{}".format(channel) r.publish(channel, json.dumps({ 'lower_index': instance.lower_index, 'bubble_sort': str(url), 'event_type': 'swap' }))
def list(self, *args, **kwargs): return Response({ 'allowance': reverse_lazy('reports-allowance', request=self.request), 'export': reverse_lazy('reports-export', request=self.request), 'rates': reverse_lazy('reports-rates', request=self.request), 'savings': reverse_lazy('reports-savings', request=self.request), 'stats': reverse_lazy('reports-stats', request=self.request), 'summary': reverse_lazy('reports-summary', request=self.request), 'week': reverse_lazy('reports-week', request=self.request), })
def list(self, request): """ Return a list of all settings. """ result = list() for association in models.Association.objects.all(): result.append({ 'name': association.name, 'entry': association.entry, 'url': reverse_lazy("setting-detail", kwargs={ 'pk': association.id }, request=request) }) return Response(result)
def save_game_of_life(sender, instance, **kwargs): if instance.is_async: return if instance.is_buffer: return class_name = instance.interaction.clicker_class.class_name channel = 'gameoflife.{}.client'.format(class_name) url = reverse_lazy('gameoflife-detail', args=[instance.id]) print "Publishing to redis:{}".format(channel) r.publish(channel, json.dumps({ 'game_of_life': str(url), 'event_type': 'next_state', 'serialized': unicode(instance) }))
def get(self,request): recruitment_info=RecruitmentInformation.objects.filter(department=request.user) data={} approved_recruitment_info = recruitment_info.filter(is_varified=True) pending_recruitment_info = recruitment_info.filter(is_varified=False) denied_recruitment_info = recruitment_info.filter(is_denied=True) applications = Application.objects.filter_by_department(user=request.user) applying = applications.filter(status='w') pending = applications.filter(status='s') data['approved_recruitment_info']=[list for each in approved_recruitment_info] data['approved_recruitment_info']=PostListSerializer( approved_recruitment_info, many=True, context={'request': request} ).data data['pending_recruitment_info']=PostListSerializer( pending_recruitment_info, many=True, context={'request': request} ).data data['denied_recruitment_info']=PostListSerializer( denied_recruitment_info, many=True, context={'request': request} ).data data['applying'] = ApplicationListSerializer( applying, many=True, context={'request': request} ).data data['pending'] = ApplicationListSerializer( pending, many=True, context={'request': request} ).data #cause in our serializers, we called anther funcyions so we must have context={'request': request} data['revers test']=reverse_lazy('users-api:login',request=request) return Response(data)
def get(self, request): # # Keyword arguments for the reversion # kwargs = {"request": request, "format": settings.API_FORMAT} # # Create HTTP response # return Response( { "me": reverse_lazy("me", **kwargs), "users": reverse_lazy("user-list", **kwargs), "memes": reverse_lazy("meme-list", **kwargs), "posts": reverse_lazy("post-list", **kwargs), "likes": reverse_lazy("like-list", **kwargs), "comments": reverse_lazy("comment-list", **kwargs), "friendships": reverse_lazy("friendship-list", **kwargs), }, status=status.HTTP_200_OK, )
def save_game_of_life_cell(sender, instance, **kwargs): if instance.game_of_life.is_buffer: return if instance.game_of_life.interaction.state != Interaction.ACTIVE: return if not instance.changed: return class_name = instance.game_of_life.interaction.clicker_class.class_name channel = '{}gameoflife.{}.client'.format('async' if instance.game_of_life.is_async else '', class_name) url = reverse_lazy('gameoflife-detail', args=[instance.game_of_life_id]) print "Publishing to redis:{}".format(channel) r.publish(channel, json.dumps({ 'row': instance.row, 'col': instance.col, 'alive': instance.alive, 'game_of_life': str(url), 'event_type': 'toggle_cell' }))
def get_parent_url(self, obj): return reverse_lazy('api-root', request=self.context.get('request'))
def get_links(self, obj): request = self.context['request'] return { 'self': reverse_lazy('sprint-detail', kwargs={'pk': obj.pk}, request=request), }
def generate(self, request, **kwargs): """ :param class_name: the class this interaction will be associated with """ try: if request.DATA: data = request.DATA else: data = request.stream.DATA except Exception: data = request.stream.DATA async = data.get('async', False) is True if request.method == 'GET': return Response({}, status=status.HTTP_200_OK) if not hasattr(request.user, 'creator'): return Response({'detail': 'you are not a creator'}, status=status.HTTP_403_FORBIDDEN) creator = request.user.creator class_name = data['class_name'] clicker_class = models.ClickerClass.objects.get(class_name=class_name) class_size = clicker_class.get_connected_devices() if class_size == 0: return Response({'detail': 'class size is zero'}, status=status.HTTP_403_FORBIDDEN) # if 'interaction_slug' not in request.data: # return Response({'detail': 'please specify an interaction type'}, status=status.HTTP_400_BAD_REQUEST) activate = data.get('activate', GameOfLifeViewSet.DEFAULT_ACTIVATE) # interaction_slug = request.data['interaction_slug'] interaction_type = models.InteractionType.objects.get(slug_name='gameoflife') for m in models.Interaction.objects.all(): if activate: m.state = models.Interaction.COMPLETE m.save() # create game of life instance and corresponding interaction interaction = models.Interaction.objects.create(clicker_class=clicker_class, state=models.Interaction.READY, creator=creator, interaction_type=interaction_type) interaction.save() rows = max(4, int(math.ceil(math.sqrt(class_size)))) cols = max(4, int(math.ceil(float(class_size) / rows))) # more-or-less square game = models.GameOfLife(num_rows=rows, num_cols=cols, interaction=interaction, is_async=async) game.save() if not async: gol_buffer = models.GameOfLife(num_rows=rows, num_cols=cols, is_async=False, is_buffer=True) gol_buffer.save() game.buffer = gol_buffer game.save() interaction.gameoflife = game if activate: interaction.state = models.Interaction.ACTIVE interaction.save() # allocate clients to cells def rand_bool(): return random.randrange(2) == 0 clients = map(lambda d: d.device_id, clicker_class.registereddevice_set.all()) ai = [True] * ((rows * cols) - class_size) everything = clients + ai random.shuffle(everything) # assign cell states randomly interaction_data = {'assignments': {}} patterns = { 'glider': ( (0, 0, 1, 0), (1, 0, 1, 0), (0, 1, 1, 0), (0, 0, 0, 0), ) } pattern_name = data.get('pattern', GameOfLifeViewSet.DEFAULT_PATTERN) if pattern_name in patterns: pattern = patterns[pattern_name] else: pattern = None for col in range(cols): for row in range(rows): cell = game.cells.filter(game_of_life=game, row=row, col=col)[0] if pattern: if row < len(pattern) and col < len(pattern[0]): cell.alive = bool(pattern[row][col]) else: cell.alive = False # could use rand_bool() here. else: cell.alive = rand_bool() if not async: buff_cell = gol_buffer.cells.filter(game_of_life=gol_buffer, row=row, col=col)[0] something = everything.pop() if isinstance(something, unicode): device_id = something cell.save() cell_data = serializers.GameOfLifeCellSerializer(cell, context={'request': request}).data if async: interaction_data['assignments'][device_id] = cell_data else: buff_cell_data = serializers.GameOfLifeCellSerializer(buff_cell, context={'request': request}).data interaction_data['assignments'][device_id] = { 'source': cell_data, 'buffer': buff_cell_data } else: cell.is_ai = True cell.save() if not async: buff_cell.is_ai = cell.is_ai buff_cell.alive = cell.alive buff_cell.save() interaction_data['urls'] = { 'source': str(reverse_lazy('gameoflife-detail', args=[game.id])), } if not async: interaction_data['urls']['buffer'] = str(reverse_lazy('gameoflife-detail', args=[gol_buffer.id])) interaction_data['urls']['next_state'] = "{}swap_buffers/".format(interaction_data['urls']['source']) interaction_data['interaction'] = interaction.id interaction_data['game_of_life'] = game.id if async: interaction_data['instance_script'] = '/static/js/:type:/asyncgameoflife.bundle.js' interaction_data['instance_component_name'] = 'AsyncGameOfLife' else: # interaction_data['game_of_life_buffer'] = game_buffer.id interaction_data['instance_script'] = '/static/js/:type:/gameoflife.bundle.js' interaction_data['instance_component_name'] = 'GameOfLife' interaction.data_json = json.dumps(interaction_data) interaction.save() return Response(serializers.GameOfLifeSerializer(game, context={'request': request}).data, status=status.HTTP_201_CREATED)
def get_url(self, obj, view_name, request, format): kwargs = {'slug': obj.slug, 'course_slug': obj.course.slug} return reverse_lazy(view_name, kwargs=kwargs, request=request, format=format)
def is_post_request(request, response): return request.method == "POST" @ratelimit("def", periods=["1m"], increment=is_post_request) def admin_login(request): show_captcha = getattr(request, "limits", {"def": [0]})["def"][0] >= block_limit authentication_form = ( create_form_subclass_with_recaptcha(AdminLoginForm, recaptcha_client) if show_captcha else AdminLoginForm ) return auth_views.login(request, authentication_form=authentication_form) @login_required(login_url=reverse_lazy("admin_login")) @permission_required("portal.view_aggregated_data", raise_exception=True) def aggregated_data(request): tables = [] table_head = ["Data description", "Value", "More info"] table_data = [] """ Overall statistics """ table_data.append( [ "Number of users",