def browser(request, p_id, p_chrom=None, p_start=None, p_end=None): perc_move = (0.5, 0.25) perc_zoom = 1.25 p_plot = Plot.objects.get(id=p_id) p_columns_dict = p_plot.getColumnsDict() c_chrom, c_start, c_end, c_interval_start, c_interval_end = getPlotCookie( request, p_id) if p_chrom is None: p_chrom = c_chrom p_start = c_start p_end = c_end p_name_filters = sorted(p_plot.getNameFilters(p_chrom, p_start, p_end)) name_filter = '' get_url = '' results = '' if request.method == 'GET': search_text = request.GET.get('search_text', '') name_filter = request.GET.get('name_filter', '') interval_start = request.GET.get('interval_start', c_interval_start or '') interval_end = request.GET.get('interval_end', c_interval_end or '') p_interval_start = request.GET.get('interval_start', c_interval_start) p_interval_end = request.GET.get('interval_end', c_interval_end) setPlotCookie(request, p_id, p_chrom, p_start, p_end, p_interval_start, p_interval_end) region_or_err_msg = get_region_or_err_msg(search_text, p_id) if len(region_or_err_msg) == 3: p_chrom, p_start, p_end = region_or_err_msg elif search_text == '': pass else: messages.error(request, region_or_err_msg) get_url = '?' + urlencode( { 'name_filter': name_filter, 'interval_start': interval_start, 'interval_end': interval_end }, quote_via=quote_plus) if p_plot.hasEval( ) and p_interval_start is not None and p_interval_end is not None: results = ranking(p_plot.eval, p_chrom, p_interval_start, p_interval_end) else: pass return TemplateResponse( request, 'hictracks/browser.html', { 'p_id': p_id, 'p_plot': p_plot, 'p_name_filters': p_name_filters, 'p_columns_dict': p_columns_dict, 'p_cols': len(p_columns_dict, ), 'p_chrom': p_chrom, 'p_start': p_start, 'p_end': p_end, 'name_filter': name_filter, 'move': (move(p_start, p_end, perc_move[0], False), move(p_start, p_end, perc_move[1], False), move(p_start, p_end, perc_move[1], True), move(p_start, p_end, perc_move[0], True)), 'zoom_in': zoom(p_start, p_end, perc_zoom, True), 'zoom_out': zoom(p_start, p_end, perc_zoom, False), 'region_len': p_end - p_start, 'get_url': get_url, 'results': results, 'interval_start': interval_start, 'interval_end': interval_end })
def post(self, request, object_id, *args, **kwargs): object_id = unquote(object_id) self.obj = self.get_object(object_id) if not self.has_change_permission(self.obj): raise PermissionDenied params = self.request.POST if 'version_a' not in params or 'version_b' not in params: self.message_user(_("Must select two versions."), 'error') return self.get_response() version_a_id = params['version_a'] version_b_id = params['version_b'] if version_a_id == version_b_id: self.message_user( _("Please select two different versions."), 'error') return self.get_response() version_a = get_object_or_404(Version, pk=version_a_id) version_b = get_object_or_404(Version, pk=version_b_id) diffs = [] obj_a, detail_a = self.get_version_object(version_a) obj_b, detail_b = self.get_version_object(version_b) for f in (self.opts.fields + self.opts.many_to_many): if is_related_field2(f): label = f.opts.verbose_name else: label = f.verbose_name value_a = f.value_from_object(obj_a) value_b = f.value_from_object(obj_b) is_diff = value_a != value_b if type(value_a) in (list, tuple) and type(value_b) in (list, tuple) \ and len(value_a) == len(value_b) and is_diff: is_diff = False for i in xrange(len(value_a)): if value_a[i] != value_a[i]: is_diff = True break if type(value_a) is QuerySet and type(value_b) is QuerySet: is_diff = list(value_a) != list(value_b) diffs.append((label, detail_a.get_field_result( f.name).val, detail_b.get_field_result(f.name).val, is_diff)) context = super(RevisionListView, self).get_context() context.update({ 'object': self.obj, 'opts': self.opts, 'version_a': version_a, 'version_b': version_b, 'revision_a_url': self.model_admin_url('revision', quote(version_a.object_id), version_a.id), 'revision_b_url': self.model_admin_url('revision', quote(version_b.object_id), version_b.id), 'diffs': diffs }) return TemplateResponse( self.request, self.revision_diff_template or self.get_template_list('views/revision_diff.html'), context)
def index(request): Document = get_document_model() # Get documents (filtered by user permission) documents = permission_policy.instances_user_has_any_permission_for( request.user, ['change', 'delete']) # Ordering if 'ordering' in request.GET and request.GET['ordering'] in [ 'title', '-created_at' ]: ordering = request.GET['ordering'] else: ordering = '-created_at' documents = documents.order_by(ordering) # Filter by collection current_collection = None collection_id = request.GET.get('collection_id') if collection_id: try: current_collection = Collection.objects.get(id=collection_id) documents = documents.filter(collection=current_collection) except (ValueError, Collection.DoesNotExist): pass # Search query_string = None if 'q' in request.GET: form = SearchForm(request.GET, placeholder=_("Search documents")) if form.is_valid(): query_string = form.cleaned_data['q'] documents = documents.search(query_string) else: form = SearchForm(placeholder=_("Search documents")) # Pagination paginator = Paginator(documents, per_page=20) documents = paginator.get_page(request.GET.get('p')) collections = permission_policy.collections_user_has_any_permission_for( request.user, ['add', 'change']) if len(collections) < 2: collections = None # Create response if request.is_ajax(): return TemplateResponse( request, 'wagtaildocs/documents/results.html', { 'ordering': ordering, 'documents': documents, 'query_string': query_string, 'is_searching': bool(query_string), }) else: return TemplateResponse( request, 'wagtaildocs/documents/index.html', { 'ordering': ordering, 'documents': documents, 'query_string': query_string, 'is_searching': bool(query_string), 'search_form': form, 'popular_tags': popular_tags_for_model(Document), 'user_can_add': permission_policy.user_has_permission(request.user, 'add'), 'collections': collections, 'current_collection': current_collection, })
def status_beholder(request): context = {} timestamp = None if request.method == 'POST': time_string = request.POST.get('time') timestamp = parse_time(time_string) elif request.method == 'GET': if request.GET.has_key('time'): time_string = request.GET.get('time') timestamp = parse_time(time_string) if timestamp: status = BeholderStatus.objects.filter(time__lte=timestamp).order_by('-time').first() if status: context['status'] = status.status context['time'] = status.time channels = [] mounts = [] for id in range(0, int(status.status['nchannels'])): channel = extract_status(status.status, 'channel%d' % (id + 1)) channel['connected'] = status.status['channel%d' % (id + 1)] channels.append(channel) for id in range(0, int(status.status['nmounts'])): mount = extract_status(status.status, 'mount%d' % (id + 1)) mount['hw_connected'] = status.status['mount%d_connected' % (id + 1)] mount['connected'] = status.status['mount%d' % (id + 1)] mounts.append(mount) context['channels'] = channels context['mounts'] = mounts scheduler = extract_status(status.status, 'scheduler') scheduler['connected'] = status.status['scheduler'] context['scheduler'] = scheduler weather = extract_status(status.status, 'weather') weather['connected'] = status.status['weather'] context['weather'] = weather dome = extract_status(status.status, 'dome') dome['connected'] = status.status['dome'] context['dome'] = dome can = extract_status(status.status, 'can') if can: chillers = [] for id in range(0, int(status.status['can_nchillers'])): chiller = {'state':status.status['can_chiller%s_state' % (id + 1)], 'name':'C%d' % (id + 1), 'namestate':'C%d:%s' % (id + 1, status.status['can_chiller%s_state' % (id + 1)])} chillers.append(chiller) can['chillers'] = chillers context['can'] = can context['timestamp'] = timestamp return TemplateResponse(request, 'status_beholder.html', context=context)
def show_template_response(request): template = engines['django'].from_string(TEMPLATE) return TemplateResponse(request, template)
def confirm_submission(request): return TemplateResponse( request, 'jobs/confirm_submission.html' )
def test_args(self): response = TemplateResponse(self.factory.get('/'), '', {}, 'application/json', 504) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 504)
def grant_details(request, grant_id, grant_slug): """Display the Grant details page.""" tab = request.GET.get('tab', 'activity') profile = get_profile(request) add_cancel_params = False try: grant = Grant.objects.prefetch_related('subscriptions', 'milestones', 'updates', 'team_members').get( pk=grant_id, slug=grant_slug ) milestones = grant.milestones.order_by('due_date') updates = grant.updates.order_by('-created_on') subscriptions = grant.subscriptions.filter(active=True, error=False).order_by('-created_on') cancelled_subscriptions = grant.subscriptions.filter(active=False, error=False).order_by('-created_on') activity_count = grant.contribution_count contributors = [] contributions = [] voucher_fundings = [] if tab in ['transactions', 'contributors']: _contributions = Contribution.objects.filter(subscription__in=grant.subscriptions.all().cache(timeout=60)).cache(timeout=60) phantom_funds = grant.phantom_funding.all().cache(timeout=60) contributions = list(_contributions.order_by('-created_on')) voucher_fundings = [ele.to_mock_contribution() for ele in phantom_funds.order_by('-created_on')] contributors = list(_contributions.distinct('subscription__contributor_profile')) + list(phantom_funds.distinct('profile')) activity_count = len(cancelled_subscriptions) + len(contributions) user_subscription = grant.subscriptions.filter(contributor_profile=profile, active=True).first() user_non_errored_subscription = grant.subscriptions.filter(contributor_profile=profile, active=True, error=False).first() add_cancel_params = user_subscription except Grant.DoesNotExist: raise Http404 is_admin = (grant.admin_profile.id == profile.id) if profile and grant.admin_profile else False if is_admin: add_cancel_params = True is_team_member = is_grant_team_member(grant, profile) if request.method == 'POST' and (is_team_member or request.user.is_staff): if request.FILES.get('input_image'): logo = request.FILES.get('input_image', None) grant.logo = logo grant.save() record_grant_activity_helper('update_grant', grant, profile) return redirect(reverse('grants:details', args=(grant.pk, grant.slug))) if 'contract_address' in request.POST: grant.cancel_tx_id = request.POST.get('grant_cancel_tx_id', '') grant.active = False grant.save() grant_cancellation(grant, user_subscription) for sub in subscriptions: subscription_terminated(grant, sub) record_grant_activity_helper('killed_grant', grant, profile) elif 'input-title' in request.POST: update_kwargs = { 'title': request.POST.get('input-title', ''), 'description': request.POST.get('description', ''), 'grant': grant } Update.objects.create(**update_kwargs) record_grant_activity_helper('update_grant', grant, profile) elif 'edit-title' in request.POST: grant.title = request.POST.get('edit-title') grant.reference_url = request.POST.get('edit-reference_url') grant.amount_goal = Decimal(request.POST.get('edit-amount_goal')) team_members = request.POST.getlist('edit-grant_members[]') team_members.append(str(grant.admin_profile.id)) grant.team_members.set(team_members) if 'edit-description' in request.POST: grant.description = request.POST.get('edit-description') grant.description_rich = request.POST.get('edit-description_rich') grant.save() form_category_ids = request.POST.getlist('edit-categories[]') '''Overwrite the existing categories and then add the new ones''' grant.categories.clear() add_form_categories_to_grant(form_category_ids, grant, grant.grant_type) record_grant_activity_helper('update_grant', grant, profile) return redirect(reverse('grants:details', args=(grant.pk, grant.slug))) # handle grant updates unsubscribe key = 'unsubscribed_profiles' is_unsubscribed_from_updates_from_this_grant = request.user.is_authenticated and request.user.profile.pk in grant.metadata.get(key, []) if request.GET.get('unsubscribe') and request.user.is_authenticated: ups = grant.metadata.get(key, []) ups.append(request.user.profile.pk) grant.metadata[key] = ups grant.save() messages.info( request, _('You have been unsubscribed from the updates from this grant.') ) is_unsubscribed_from_updates_from_this_grant = True params = { 'active': 'grant_details', 'clr_matching_banners_style': clr_matching_banners_style, 'grant': grant, 'tab': tab, 'title': matching_live + grant.title, 'card_desc': grant.description, 'avatar_url': grant.logo.url if grant.logo else None, 'subscriptions': subscriptions, 'cancelled_subscriptions': cancelled_subscriptions, 'contributions': contributions, 'user_subscription': user_subscription, 'user_non_errored_subscription': user_non_errored_subscription, 'is_admin': is_admin, 'grant_is_inactive': not grant.active, 'updates': updates, 'milestones': milestones, 'keywords': get_keywords(), 'target': f'/activity?what=grant:{grant.pk}', 'activity_count': activity_count, 'contributors': contributors, 'clr_active': clr_active, 'show_clr_card': show_clr_card, 'is_team_member': is_team_member, 'voucher_fundings': voucher_fundings, 'is_unsubscribed_from_updates_from_this_grant': is_unsubscribed_from_updates_from_this_grant, 'tags': [(f'Email Grant Funders ({len(contributors)})', 'bullhorn')] if is_team_member else [], } if tab == 'stats': params['max_graph'] = grant.history_by_month_max params['history'] = json.dumps(grant.history_by_month) if add_cancel_params: add_in_params = { 'recommend_gas_price': recommend_min_gas_price_to_confirm_in_time(4), 'recommend_gas_price_slow': recommend_min_gas_price_to_confirm_in_time(120), 'recommend_gas_price_avg': recommend_min_gas_price_to_confirm_in_time(15), 'recommend_gas_price_fast': recommend_min_gas_price_to_confirm_in_time(1), 'eth_usd_conv_rate': eth_usd_conv_rate(), 'conf_time_spread': conf_time_spread(), 'gas_advisories': gas_advisories(), } for key, value in add_in_params.items(): params[key] = value return TemplateResponse(request, 'grants/detail/index.html', params)
def grant_new(request): """Handle new grant.""" profile = get_profile(request) if request.method == 'POST': if 'title' in request.POST: logo = request.FILES.get('input_image', None) receipt = json.loads(request.POST.get('receipt', '{}')) team_members = request.POST.getlist('team_members[]') grant_type = request.POST.get('grant_type', 'tech') grant_kwargs = { 'title': request.POST.get('title', ''), 'description': request.POST.get('description', ''), 'description_rich': request.POST.get('description_rich', ''), 'reference_url': request.POST.get('reference_url', ''), 'admin_address': request.POST.get('admin_address', ''), 'contract_owner_address': request.POST.get('contract_owner_address', ''), 'token_address': request.POST.get('token_address', ''), 'token_symbol': request.POST.get('token_symbol', ''), 'amount_goal': request.POST.get('amount_goal', 1), 'contract_version': request.POST.get('contract_version', ''), 'deploy_tx_id': request.POST.get('transaction_hash', ''), 'network': request.POST.get('network', 'mainnet'), 'metadata': receipt, 'admin_profile': profile, 'logo': logo, 'hidden': False, 'clr_prediction_curve': [[0.0, 0.0, 0.0] for x in range(0, 6)], 'grant_type': grant_type } grant = Grant.objects.create(**grant_kwargs) new_grant_admin(grant) team_members = (team_members[0].split(',')) team_members.append(profile.id) team_members = list(set(team_members)) team_members = [int(i) for i in team_members if i != ''] grant.team_members.add(*team_members) grant.save() form_category_ids = request.POST.getlist('categories[]') form_category_ids = (form_category_ids[0].split(',')) form_category_ids = list(set(form_category_ids)) add_form_categories_to_grant(form_category_ids, grant, grant_type) return JsonResponse({ 'success': True, }) if 'contract_address' in request.POST: tx_hash = request.POST.get('transaction_hash', '') if not tx_hash: return JsonResponse({ 'success': False, 'info': 'no tx hash', 'url': None, }) grant = Grant.objects.filter(deploy_tx_id=tx_hash).first() grant.contract_address = request.POST.get('contract_address', '') print(tx_hash, grant.contract_address) messages.info( request, _('Thank you for posting this Grant. Share the Grant URL with your friends/followers to raise your first tokens.') ) grant.save() record_grant_activity_helper('new_grant', grant, profile) new_grant(grant, profile) return JsonResponse({ 'success': True, 'url': reverse('grants:details', args=(grant.pk, grant.slug)) }) params = { 'active': 'new_grant', 'title': _('New Grant'), 'card_desc': _('Provide sustainable funding for Open Source with Gitcoin Grants'), 'profile': profile, 'grant': {}, 'keywords': get_keywords(), 'recommend_gas_price': recommend_min_gas_price_to_confirm_in_time(4), 'recommend_gas_price_slow': recommend_min_gas_price_to_confirm_in_time(120), 'recommend_gas_price_avg': recommend_min_gas_price_to_confirm_in_time(15), 'recommend_gas_price_fast': recommend_min_gas_price_to_confirm_in_time(1), 'eth_usd_conv_rate': eth_usd_conv_rate(), 'conf_time_spread': conf_time_spread(), 'gas_advisories': gas_advisories(), 'trusted_relayer': settings.GRANTS_OWNER_ACCOUNT } return TemplateResponse(request, 'grants/new.html', params)
def password_reset_done(request): return TemplateResponse(request, 'password_reset_done.html', None)
def verify_email_required(request): if request.user.email_verified: messages.warning(request, "Your email has already been verified") return HttpResponseRedirect(reverse('root')) return TemplateResponse(request, 'verify_email_required.html', None)
def template_response(self, template, context): return TemplateResponse(self.request, template, context)
def password_reset_confirm_wrapper(request, uidb36=None, token=None): """ A wrapper around django.contrib.auth.views.password_reset_confirm. Needed because we want to set the user as active at this step. We also optionally do some additional password policy checks. """ # convert old-style base36-encoded user id to base64 uidb64 = uidb36_to_uidb64(uidb36) platform_name = { "platform_name": configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME) } # User can not get this link unless account recovery feature is enabled. if 'is_account_recovery' in request.GET and not is_secondary_email_feature_enabled(): raise Http404 try: uid_int = base36_to_int(uidb36) user = User.objects.get(id=uid_int) except (ValueError, User.DoesNotExist): # if there's any error getting a user, just let django's # password_reset_confirm function handle it. return password_reset_confirm( request, uidb64=uidb64, token=token, extra_context=platform_name ) if UserRetirementRequest.has_user_requested_retirement(user): # Refuse to reset the password of any user that has requested retirement. context = { 'validlink': True, 'form': None, 'title': _('Password reset unsuccessful'), 'err_msg': _('Error in resetting your password.'), } context.update(platform_name) return TemplateResponse( request, 'registration/password_reset_confirm.html', context ) if waffle().is_enabled(PREVENT_AUTH_USER_WRITES): context = { 'validlink': False, 'form': None, 'title': _('Password reset unsuccessful'), 'err_msg': SYSTEM_MAINTENANCE_MSG, } context.update(platform_name) return TemplateResponse( request, 'registration/password_reset_confirm.html', context ) if request.method == 'POST': # We have to make a copy of request.POST because it is a QueryDict object which is immutable until copied. # We have to use request.POST because the password_reset_confirm method takes in the request and a user's # password is set to the request.POST['new_password1'] field. We have to also normalize the new_password2 # field so it passes the equivalence check that new_password1 == new_password2 # In order to switch out of having to do this copy, we would want to move the normalize_password code into # a custom User model's set_password method to ensure it is always happening upon calling set_password. request.POST = request.POST.copy() request.POST['new_password1'] = normalize_password(request.POST['new_password1']) request.POST['new_password2'] = normalize_password(request.POST['new_password2']) password = request.POST['new_password1'] try: validate_password(password, user=user) except ValidationError as err: # We have a password reset attempt which violates some security # policy, or any other validation. Use the existing Django template to communicate that # back to the user. context = { 'validlink': True, 'form': None, 'title': _('Password reset unsuccessful'), 'err_msg': ' '.join(err.messages), } context.update(platform_name) return TemplateResponse( request, 'registration/password_reset_confirm.html', context ) # remember what the old password hash is before we call down old_password_hash = user.password if 'is_account_recovery' in request.GET: response = password_reset_confirm( request, uidb64=uidb64, token=token, extra_context=platform_name, template_name='registration/password_reset_confirm.html', post_reset_redirect='signin_user', ) else: response = password_reset_confirm( request, uidb64=uidb64, token=token, extra_context=platform_name ) # If password reset was unsuccessful a template response is returned (status_code 200). # Check if form is invalid then show an error to the user. # Note if password reset was successful we get response redirect (status_code 302). if response.status_code == 200: form_valid = response.context_data['form'].is_valid() if response.context_data['form'] else False if not form_valid: log.warning( u'Unable to reset password for user [%s] because form is not valid. ' u'A possible cause is that the user had an invalid reset token', user.username, ) response.context_data['err_msg'] = _('Error in resetting your password. Please try again.') return response # get the updated user updated_user = User.objects.get(id=uid_int) if 'is_account_recovery' in request.GET: try: updated_user.email = updated_user.account_recovery.secondary_email updated_user.account_recovery.delete() # emit an event that the user changed their secondary email to the primary email tracker.emit( SETTING_CHANGE_INITIATED, { "setting": "email", "old": user.email, "new": updated_user.email, "user_id": updated_user.id, } ) except ObjectDoesNotExist: log.error( 'Account recovery process initiated without AccountRecovery instance for user {username}'.format( username=updated_user.username ) ) updated_user.save() if response.status_code == 302 and 'is_account_recovery' in request.GET: messages.success( request, HTML(_( '{html_start}Password Creation Complete{html_end}' 'Your password has been created. {bold_start}{email}{bold_end} is now your primary login email.' )).format( support_url=configuration_helpers.get_value('SUPPORT_SITE_LINK', settings.SUPPORT_SITE_LINK), html_start=HTML('<p class="message-title">'), html_end=HTML('</p>'), bold_start=HTML('<b>'), bold_end=HTML('</b>'), email=updated_user.email, ), extra_tags='account-recovery aa-icon submission-success' ) else: response = password_reset_confirm( request, uidb64=uidb64, token=token, extra_context=platform_name ) response_was_successful = response.context_data.get('validlink') if response_was_successful and not user.is_active: user.is_active = True user.save() return response
def styleguide(request): return TemplateResponse(request, 'styleguide.html')
def template_list_view(request): """ For testing resolving a list of templates """ return TemplateResponse(request, ["doesntexist.html", "basic.html"])
def grant_new_v0(request): """Create a v0 version of a grant contract.""" profile = get_profile(request) if request.method == 'POST': if 'title' in request.POST: logo = request.FILES.get('input_image', None) receipt = json.loads(request.POST.get('receipt', '{}')) team_members = request.POST.getlist('team_members[]') grant_kwargs = { 'title': request.POST.get('title', ''), 'description': request.POST.get('description', ''), 'reference_url': request.POST.get('reference_url', ''), 'admin_address': request.POST.get('admin_address', ''), 'contract_owner_address': request.POST.get('contract_owner_address', ''), 'token_address': request.POST.get('token_address', ''), 'token_symbol': request.POST.get('token_symbol', ''), 'amount_goal': request.POST.get('amount_goal', 1), 'contract_version': request.POST.get('contract_version', ''), 'deploy_tx_id': request.POST.get('transaction_hash', ''), 'network': request.POST.get('network', 'mainnet'), 'metadata': receipt, 'admin_profile': profile, 'logo': logo, } grant = Grant.objects.create(**grant_kwargs) team_members = (team_members[0].split(',')) team_members.append(profile.id) team_members = list(set(team_members)) for i in range(0, len(team_members)): team_members[i] = int(team_members[i]) grant.team_members.add(*team_members) grant.save() return JsonResponse({ 'success': True, }) if 'contract_address' in request.POST: tx_hash = request.POST.get('transaction_hash', '') if not tx_hash: return JsonResponse({ 'success': False, 'info': 'no tx hash', 'url': None, }) grant = Grant.objects.filter(deploy_tx_id=tx_hash).first() grant.contract_address = request.POST.get('contract_address', '') print(tx_hash, grant.contract_address) grant.save() record_grant_activity_helper('new_grant', grant, profile) new_grant(grant, profile) return JsonResponse({ 'success': True, 'url': reverse('grants:details', args=(grant.pk, grant.slug)) }) params = { 'active': 'new_grant', 'title': _('New Grant'), 'card_desc': _('Provide sustainable funding for Open Source with Gitcoin Grants'), 'profile': profile, 'grant': {}, 'keywords': get_keywords(), 'recommend_gas_price': recommend_min_gas_price_to_confirm_in_time(4), 'recommend_gas_price_slow': recommend_min_gas_price_to_confirm_in_time(120), 'recommend_gas_price_avg': recommend_min_gas_price_to_confirm_in_time(15), 'recommend_gas_price_fast': recommend_min_gas_price_to_confirm_in_time(1), 'eth_usd_conv_rate': eth_usd_conv_rate(), 'conf_time_spread': conf_time_spread(), 'gas_advisories': gas_advisories(), 'trusted_relayer': settings.GRANTS_OWNER_ACCOUNT } return TemplateResponse(request, 'grants/newv0.html', params)
def index(request): return TemplateResponse(request, 'administrator/index3.html')
def grant_fund(request, grant_id, grant_slug): """Handle grant funding.""" try: grant = Grant.objects.get(pk=grant_id, slug=grant_slug) except Grant.DoesNotExist: raise Http404 profile = get_profile(request) if not grant.active: params = { 'active': 'grant_error', 'title': _('Fund - Grant Ended'), 'grant': grant, 'text': _('This Grant has ended.'), 'subtext': _('Contributions can no longer be made this grant') } return TemplateResponse(request, 'grants/shared/error.html', params) if is_grant_team_member(grant, profile): params = { 'active': 'grant_error', 'title': _('Fund - Grant funding blocked'), 'grant': grant, 'text': _('This Grant cannot be funded'), 'subtext': _('Grant team members cannot contribute to their own grant.') } return TemplateResponse(request, 'grants/shared/error.html', params) if grant.link_to_new_grant: params = { 'active': 'grant_error', 'title': _('Fund - Grant Migrated'), 'grant': grant.link_to_new_grant, 'text': f'This Grant has ended', 'subtext': 'Contributions can no longer be made to this grant. <br> Visit the new grant to contribute.', 'button_txt': 'View New Grant' } return TemplateResponse(request, 'grants/shared/error.html', params) active_subscription = Subscription.objects.select_related('grant').filter( grant=grant_id, active=True, error=False, contributor_profile=request.user.profile ) if active_subscription: params = { 'active': 'grant_error', 'title': _('Subscription Exists'), 'grant': grant, 'text': _('You already have an active subscription for this grant.') } return TemplateResponse(request, 'grants/shared/error.html', params) if grant.contract_address == '0x0': messages.info( request, _('This grant is not configured to accept funding at this time. Please contact [email protected] if you believe this message is in error!') ) logger.error(f"Grant {grant.pk} is not properly configured for funding. Please set grant.contract_address on this grant") return redirect(reverse('grants:details', args=(grant.pk, grant.slug))) if request.method == 'POST': if 'contributor_address' in request.POST: subscription = Subscription() subscription.active = False subscription.contributor_address = request.POST.get('contributor_address', '') subscription.amount_per_period = request.POST.get('amount_per_period', 0) subscription.real_period_seconds = request.POST.get('real_period_seconds', 2592000) subscription.frequency = request.POST.get('frequency', 30) subscription.frequency_unit = request.POST.get('frequency_unit', 'days') subscription.token_address = request.POST.get('token_address', '') subscription.token_symbol = request.POST.get('token_symbol', '') subscription.gas_price = request.POST.get('gas_price', 0) subscription.new_approve_tx_id = request.POST.get('sub_new_approve_tx_id', '0x0') subscription.num_tx_approved = request.POST.get('num_tx_approved', 1) subscription.network = request.POST.get('network', '') subscription.contributor_profile = profile subscription.grant = grant subscription.comments = request.POST.get('comment', '') subscription.save() # one time payments activity = None if int(subscription.num_tx_approved) == 1: subscription.successful_contribution(subscription.new_approve_tx_id); subscription.error = True #cancel subs so it doesnt try to bill again subscription.subminer_comments = "skipping subminer bc this is a 1 and done subscription, and tokens were alredy sent" subscription.save() activity = record_subscription_activity_helper('new_grant_contribution', subscription, profile) else: activity = record_subscription_activity_helper('new_grant_subscription', subscription, profile) if 'comment' in request.POST: comment = request.POST.get('comment') if comment and activity: comment = Comment.objects.create( profile=request.user.profile, activity=activity, comment=comment) # TODO - how do we attach the tweet modal WITH BULK TRANSFER COUPON next pageload?? messages.info( request, _('Your subscription has been created. It will bill within the next 5 minutes or so. Thank you for supporting Open Source !') ) return JsonResponse({ 'success': True, }) if 'hide_wallet_address' in request.POST: profile.hide_wallet_address = bool(request.POST.get('hide_wallet_address', False)) profile.save() if 'signature' in request.POST: sub_new_approve_tx_id = request.POST.get('sub_new_approve_tx_id', '') subscription = Subscription.objects.filter(new_approve_tx_id=sub_new_approve_tx_id).first() subscription.active = True subscription.subscription_hash = request.POST.get('subscription_hash', '') subscription.contributor_signature = request.POST.get('signature', '') if 'split_tx_id' in request.POST: subscription.split_tx_id = request.POST.get('split_tx_id', '') subscription.save_split_tx_to_contribution() if 'split_tx_confirmed' in request.POST: subscription.split_tx_confirmed = bool(request.POST.get('split_tx_confirmed', False)) subscription.save_split_tx_to_contribution() subscription.save() value_usdt = subscription.get_converted_amount() if value_usdt: grant.monthly_amount_subscribed += subscription.get_converted_monthly_amount() grant.save() new_supporter(grant, subscription) thank_you_for_supporting(grant, subscription) return JsonResponse({ 'success': True, 'url': reverse('grants:details', args=(grant.pk, grant.slug)) }) splitter_contract_address = settings.SPLITTER_CONTRACT_ADDRESS # handle phantom funding active_tab = 'normal' fund_reward = None round_number = 4 can_phantom_fund = request.user.is_authenticated and request.user.groups.filter(name='phantom_funders').exists() and clr_active phantom_funds = PhantomFunding.objects.filter(profile=request.user.profile, round_number=round_number).order_by('created_on').nocache() if request.user.is_authenticated else PhantomFunding.objects.none() is_phantom_funding_this_grant = can_phantom_fund and phantom_funds.filter(grant=grant).exists() show_tweet_modal = False if can_phantom_fund: active_tab = 'phantom' if can_phantom_fund and request.POST.get('toggle_phantom_fund'): if is_phantom_funding_this_grant: msg = "You are no longer signaling for this grant." phantom_funds.filter(grant=grant).delete() else: msg = "You are now signaling for this grant." show_tweet_modal = True name_search = 'grants_round_4_contributor' if not settings.DEBUG else 'pogs_eth' fund_reward = BulkTransferCoupon.objects.filter(token__name__contains=name_search).order_by('?').first() PhantomFunding.objects.create(grant=grant, profile=request.user.profile, round_number=round_number) record_grant_activity_helper('new_grant_contribution', grant, request.user.profile) messages.info( request, msg ) is_phantom_funding_this_grant = not is_phantom_funding_this_grant params = { 'profile': profile, 'active': 'fund_grant', 'title': _('Fund Grant'), 'card_desc': _('Provide sustainable funding for Open Source with Gitcoin Grants'), 'subscription': {}, 'show_tweet_modal': show_tweet_modal, 'grant_has_no_token': True if grant.token_address == '0x0000000000000000000000000000000000000000' else False, 'grant': grant, 'clr_prediction_curve': [c[1] for c in grant.clr_prediction_curve] if grant.clr_prediction_curve and len(grant.clr_prediction_curve[0]) > 1 else [0, 0, 0, 0, 0, 0], 'keywords': get_keywords(), 'recommend_gas_price': recommend_min_gas_price_to_confirm_in_time(4), 'recommend_gas_price_slow': recommend_min_gas_price_to_confirm_in_time(120), 'recommend_gas_price_avg': recommend_min_gas_price_to_confirm_in_time(15), 'recommend_gas_price_fast': recommend_min_gas_price_to_confirm_in_time(1), 'eth_usd_conv_rate': eth_usd_conv_rate(), 'conf_time_spread': conf_time_spread(), 'gas_advisories': gas_advisories(), 'splitter_contract_address': settings.SPLITTER_CONTRACT_ADDRESS, 'gitcoin_donation_address': settings.GITCOIN_DONATION_ADDRESS, 'can_phantom_fund': can_phantom_fund, 'is_phantom_funding_this_grant': is_phantom_funding_this_grant, 'active_tab': active_tab, 'fund_reward': fund_reward, 'phantom_funds': phantom_funds, 'clr_round': clr_round, 'clr_active': clr_active, 'total_clr_pot': total_clr_pot, } return TemplateResponse(request, 'grants/fund.html', params)
def _response(self, template='foo', *args, **kwargs): return TemplateResponse(self.factory.get('/'), Template(template), *args, **kwargs)
def quickstart(request): """Display quickstart guide.""" params = {'active': 'grants_quickstart', 'title': _('Quickstart')} return TemplateResponse(request, 'grants/quickstart.html', params)
def hard_delete_selected(modeladmin, request, queryset): opts = modeladmin.model._meta app_label = opts.app_label # Populate deletable_objects, a data structure of all related objects that # will also be deleted. deletable_objects, model_count, perms_needed, protected = modeladmin.get_deleted_objects( queryset, request) # The user has already confirmed the deletion. # Do the deletion and return None to display the change list view again. if request.POST.get('post') and not protected: if perms_needed: raise PermissionDenied n = queryset.count() if n: for obj in queryset: obj_display = str(obj) modeladmin.log_deletion(request, obj, obj_display) modeladmin.hard_delete_queryset(request, queryset) modeladmin.message_user( request, _("Successfully deleted %(count)d %(items)s.") % { "count": n, "items": model_ngettext(modeladmin.opts, n) }, messages.SUCCESS) # Return None to display the change list page again. return None objects_name = model_ngettext(queryset) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": objects_name} else: title = _("Are you sure?") context = { **modeladmin.admin_site.each_context(request), 'title': title, 'objects_name': str(objects_name), 'deletable_objects': [deletable_objects], 'model_count': dict(model_count).items(), 'queryset': queryset, 'perms_lacking': perms_needed, 'protected': protected, 'opts': opts, 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME, 'media': modeladmin.media, 'action_name': 'hard_delete_selected', } request.current_app = modeladmin.admin_site.name # Display the confirmation page return TemplateResponse( request, modeladmin.delete_selected_confirmation_template or [ "boost/admin/%s/%s/hard_delete_selected_confirmation.html" % (app_label, opts.model_name), "boost/admin/%s/hard_delete_selected_confirmation.html" % app_label, "boost/admin/hard_delete_selected_confirmation.html" ], context)
def grants(request): """Handle grants explorer.""" limit = request.GET.get('limit', 6) page = request.GET.get('page', 1) sort = request.GET.get('sort_option', 'weighted_shuffle') network = request.GET.get('network', 'mainnet') keyword = request.GET.get('keyword', '') grant_type = request.GET.get('type', 'activity') state = request.GET.get('state', 'active') category = request.GET.get('category') _grants = None bg = int(request.GET.get('i', timezone.now().strftime("%j"))) % 5 show_past_clr = False sort_by_index = None sort_by_clr_pledge_matching_amount = None if 'match_pledge_amount_' in sort: sort_by_clr_pledge_matching_amount = int(sort.split('amount_')[1]) if state == 'active': _grants = Grant.objects.filter( network=network, hidden=False, grant_type=grant_type ).active().keyword(keyword).order_by(sort) else: _grants = Grant.objects.filter( network=network, hidden=False, grant_type=grant_type ).keyword(keyword).order_by(sort) clr_prediction_curve_schema_map = {10**x:x+1 for x in range(0, 5)} if sort_by_clr_pledge_matching_amount in clr_prediction_curve_schema_map.keys(): sort_by_index = clr_prediction_curve_schema_map.get(sort_by_clr_pledge_matching_amount, 0) field_name = f'clr_prediction_curve__{sort_by_index}__2' _grants = _grants.order_by(f"-{field_name}") if category: _grants = _grants.filter(Q(categories__category__icontains = category)) _grants = _grants.prefetch_related('categories') paginator = Paginator(_grants, limit) grants = paginator.get_page(page) partners = MatchPledge.objects.filter(active=True, pledge_type=grant_type) if grant_type else MatchPledge.objects.filter(active=True) now = datetime.datetime.now() current_partners = partners.filter(end_date__gte=now).order_by('-amount') past_partners = partners.filter(end_date__lt=now).order_by('-amount') current_partners_fund = 0 for partner in current_partners: current_partners_fund += partner.amount grant_amount = 0 grant_stats = Stat.objects.filter( key='grants', ).order_by('-pk') if grant_stats.exists(): grant_amount = lazy_round_number(grant_stats.first().val) tech_grants_count = Grant.objects.filter( network=network, hidden=False, grant_type='tech' ).count() media_grants_count = Grant.objects.filter( network=network, hidden=False, grant_type='media' ).count() health_grants_count = Grant.objects.filter( network=network, hidden=False, grant_type='health' ).count() categories = [category[0] for category in basic_grant_categories(grant_type)] grant_types = [ {'label': 'Tech', 'keyword': 'tech', 'count': tech_grants_count}, {'label': 'Media', 'keyword': 'media', 'count': media_grants_count}, {'label': 'Public Health', 'keyword': 'health', 'count': health_grants_count} ] params = { 'active': 'grants_landing', 'title': matching_live + str(_('Gitcoin Grants Explorer')), 'sort': sort, 'network': network, 'keyword': keyword, 'type': grant_type, 'next_round_start': next_round_start, 'now': timezone.now(), 'clr_matching_banners_style': clr_matching_banners_style, 'categories': categories, 'grant_types': grant_types, 'current_partners_fund': current_partners_fund, 'current_partners': current_partners, 'past_partners': past_partners, 'card_desc': _('Get Substantial Sustainable Funding for Your Projects with Gitcoin Grants'), 'card_player_override': 'https://www.youtube.com/embed/eVgEWSPFR2o', 'card_player_stream_override': static('v2/card/grants.mp4'), 'card_player_thumb_override': static('v2/card/grants.png'), 'grants': grants, 'target': f'/activity?what=all_grants', 'bg': bg, 'keywords': get_keywords(), 'grant_amount': grant_amount, 'total_clr_pot': total_clr_pot, 'clr_active': clr_active, 'show_clr_card': show_clr_card, 'sort_by_index': sort_by_index, 'clr_round': clr_round, 'show_past_clr': show_past_clr, 'is_staff': request.user.is_staff, 'selected_category': category } # log this search, it might be useful for matching purposes down the line if keyword: try: SearchHistory.objects.update_or_create( search_type='grants', user=request.user, data=request.GET, ip_address=get_ip(request) ) except Exception as e: logger.debug(e) pass return TemplateResponse(request, 'grants/index.html', params)
def index(request): response = TemplateResponse(request, 'play.html', {}) sessionid = request.session.session_key if not request.session.exists(sessionid): request.session.create() return response
def page(request, number): return TemplateResponse(request, 'main/page.html')
def get_response(self): context = self.get_context() return TemplateResponse(self.request, self.object_history_template or self.get_template_list('views/model_history.html'), context)
def template_view(request): """ View that uses a template instance """ template = loader.select_template(["basic.html"]) return TemplateResponse(request, template)
def edit(request, document_id): Document = get_document_model() DocumentForm = get_document_form(Document) doc = get_object_or_404(Document, id=document_id) if not permission_policy.user_has_permission_for_instance( request.user, 'change', doc): return permission_denied(request) if request.method == 'POST': original_file = doc.file form = DocumentForm(request.POST, request.FILES, instance=doc, user=request.user) if form.is_valid(): if 'file' in form.changed_data: doc = form.save(commit=False) doc.file_size = doc.file.size # Set new document file hash doc.file.seek(0) doc._set_file_hash(doc.file.read()) doc.file.seek(0) doc.save() form.save_m2m() # If providing a new document file, delete the old one. # NB Doing this via original_file.delete() clears the file field, # which definitely isn't what we want... original_file.storage.delete(original_file.name) else: doc = form.save() # Reindex the document to make sure all tags are indexed search_index.insert_or_update_object(doc) messages.success(request, _("Document '{0}' updated").format(doc.title), buttons=[ messages.button( reverse('wagtaildocs:edit', args=(doc.id, )), _('Edit')) ]) return redirect('wagtaildocs:index') else: messages.error(request, _("The document could not be saved due to errors.")) else: form = DocumentForm(instance=doc, user=request.user) try: local_path = doc.file.path except NotImplementedError: # Document is hosted externally (eg, S3) local_path = None if local_path: # Give error if document file doesn't exist if not os.path.isfile(local_path): messages.error( request, _("The file could not be found. Please change the source or delete the document" ), buttons=[ messages.button( reverse('wagtaildocs:delete', args=(doc.id, )), _('Delete')) ]) return TemplateResponse( request, "wagtaildocs/documents/edit.html", { 'document': doc, 'filesize': doc.get_file_size(), 'form': form, 'user_can_delete': permission_policy.user_has_permission_for_instance( request.user, 'delete', doc), })
def template_simple_view(request): """ Basic django templated view """ return TemplateResponse(request, "basic.html")
def user_change_password(self, request, id, form_url=''): user = self.get_object(request, unquote(id)) if not self.has_change_permission(request, user): raise PermissionDenied if user is None: raise Http404( _('%(name)s object with primary key %(key)r does not exist.') % { 'name': self.model._meta.verbose_name, 'key': escape(id), }) if request.method == 'POST': form = self.change_password_form(user, request.POST) if form.is_valid(): form.save() change_message = self.construct_change_message( request, form, None) self.log_change(request, user, change_message) msg = gettext('Password changed successfully.') messages.success(request, msg) update_session_auth_hash(request, form.user) return HttpResponseRedirect( reverse( '%s:%s_%s_change' % ( self.admin_site.name, user._meta.app_label, user._meta.model_name, ), args=(user.pk, ), )) else: form = self.change_password_form(user) fieldsets = [(None, {'fields': list(form.base_fields)})] adminForm = admin.helpers.AdminForm(form, fieldsets, {}) context = { 'title': _('Change password: %s') % escape(user.get_username()), 'adminForm': adminForm, 'form_url': form_url, 'form': form, 'is_popup': (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), 'add': True, 'change': False, 'has_delete_permission': False, 'has_change_permission': True, 'has_absolute_url': False, 'opts': self.model._meta, 'original': user, 'save_as': False, 'show_save': True, **self.admin_site.each_context(request), } request.current_app = self.admin_site.name return TemplateResponse( request, self.change_user_password_template or 'admin/auth/user/change_password.html', context, )
def view(request): return TemplateResponse(request, from_string('hi'))