我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.messages.WARNING。
def form_valid(self, form): cart = get_cart(self.request, create=True) user = authenticate(email=self.request.POST['email'], password=self.request.POST['password']) if user is not None and user.is_active: self.request.session['user_cart'] = self.request.session.session_key login(self.request, user) if cart is not None: cart.user = Profile.objects.get(id=user.id) cart.save() messages.add_message(self.request, messages.SUCCESS, 'You were successfully logged in.') return super(AuthenticationForm, self).form_valid(form) else: response = super(AuthenticationForm, self).form_invalid(form) messages.add_message(self.request, messages.WARNING, 'Wrong email or password. Please try again') return response # Logout View
def start_instances(self, request, queryset): """ Start all transmitted PostgreSQL instances Skip already running services. """ for inst in queryset: if inst.is_online: self.message_user(request, "%s is already running." % inst, messages.WARNING ) continue try: util = PGUtility(inst) util.start() except Exception, e: self.message_user(request, "%s : %s" % (e, inst), messages.ERROR) continue self.message_user(request, "%s started!" % inst)
def stop_instances(self, request, queryset): """ Stop all transmitted PostgreSQL instances Skip already stopped services. """ for inst in queryset: if not inst.is_online: self.message_user(request, "%s is already stopped." % inst, messages.WARNING ) continue try: util = PGUtility(inst) util.stop() except Exception, e: self.message_user(request, "%s : %s" % (e, inst), messages.ERROR) continue self.message_user(request, "%s stopped!" % inst)
def addmoney(request): if request.method == 'POST': amt = cents2mc(int(float(request.POST['amount']) * 100)) user_profile = UserProfile.objects.get(user=request.user) network = user_profile.network try: charge = network.authorize_card(amt, "credit", "Add Credit") network.add_credit(amt) network.capture_charge(charge.id) messages.add_message(request, messages.SUCCESS, "addmoney_stripe_success", extra_tags="billing_resp_code") return redirect("/dashboard/billing") except stripe.StripeError: logger.error("Failed to add money, stripe.CardError: %s", request) messages.add_message(request, messages.WARNING, "addmoney_stripe_error", extra_tags="billing_resp_code") return redirect("/dashboard/billing") else: return HttpResponseBadRequest()
def verify_data(self, request, queryset): for season in queryset: # Ensure SeasonPlayer objects exist for all paired players if season.league.competitor_type == 'team': pairings = TeamPlayerPairing.objects.filter(team_pairing__round__season=season) else: pairings = LonePlayerPairing.objects.filter(round__season=season) for p in pairings: SeasonPlayer.objects.get_or_create(season=season, player=p.white) SeasonPlayer.objects.get_or_create(season=season, player=p.black) # Normalize all gamelinks bad_gamelinks = 0 for p in pairings: old = p.game_link p.game_link, ok = normalize_gamelink(old) if not ok: bad_gamelinks += 1 if p.game_link != old: p.save() if bad_gamelinks > 0: self.message_user(request, '%d bad gamelinks for %s.' % (bad_gamelinks, season.name), messages.WARNING) self.message_user(request, 'Data verified.', messages.INFO)
def warnings(self): msg_list = [] round_to_close = self.round_to_close round_to_open = self.round_to_open if round_to_close is not None and round_to_close.end_date is not None and round_to_close.end_date > timezone.now() + timedelta(hours=1): time_from_now = self._time_from_now(round_to_close.end_date - timezone.now()) msg_list.append(('The round %d end date is %s from now.' % (round_to_close.number, time_from_now), messages.WARNING)) elif round_to_open is not None and round_to_open.start_date is not None and round_to_open.start_date > timezone.now() + timedelta(hours=1): time_from_now = self._time_from_now(round_to_open.start_date - timezone.now()) msg_list.append(('The round %d start date is %s from now.' % (round_to_open.number, time_from_now), messages.WARNING)) if round_to_close is not None: incomplete_pairings = PlayerPairing.objects.filter(result='', teamplayerpairing__team_pairing__round=round_to_close).nocache() | \ PlayerPairing.objects.filter(result='', loneplayerpairing__round=round_to_close).nocache() if len(incomplete_pairings) > 0: msg_list.append(('Round %d has %d pairing(s) without a result.' % (round_to_close.number, len(incomplete_pairings)), messages.WARNING)) return msg_list
def get_search_results(self, request, queryset, search_term): use_distinct = False if not search_term: return queryset, use_distinct try: return ( apply_search(queryset, search_term, self.djangoql_schema), use_distinct, ) except (DjangoQLError, ValueError, FieldError) as e: msg = text_type(e) except ValidationError as e: msg = e.messages[0] queryset = queryset.none() messages.add_message(request, messages.WARNING, msg) return queryset, use_distinct
def token_input(request): if request.method == 'POST': try: f = TokenForm(request.POST) if f.is_valid(): token = Token.get(f.cleaned_data['code']) token.use(request.team) messages.add_message(request, messages.SUCCESS, "Našel jsi %s!" % token.entity) return redirect("token:input") except Token.DoesNotExist: messages.add_message(request, messages.INFO, "Takový líste?ek neexistuje!") except (InvalidTransaction, TokenUnusableException) as e: messages.add_message(request, messages.WARNING, "%s" % e) else: f = TokenForm() return render(request, "tokens/input.html", {'form': f})
def handle(self): try: all_secrets = self.all_secrets() except OverviewHandlerException as e: messages.add_message(self.request, messages.WARNING, str(e)) return self._render() if self.request.method == "GET": return self._render(all_secrets) form = EapSecretSearchForm(self.request.POST) if not form.is_valid(): return self._render(all_secrets) search_pattern = form.cleaned_data["search_text"] if not search_pattern == '': search_result = self._search_for(all_secrets, search_pattern) else: search_result = all_secrets return self._render(search_result, search_pattern)
def handle(self): try: all_certs = self.all_certificates() except OverviewHandlerException as e: messages.add_message(self.request, messages.WARNING, str(e)) return self._render() if self.request.method == "GET": return self._render(all_certs) form = CertificateSearchForm(self.request.POST) if not form.is_valid(): return self._render(all_certs) search_pattern = form.cleaned_data["search_text"] if not search_pattern == '': search_result = self._search_for(all_certs, search_pattern) else: search_result = all_certs return self._render(search_result, search_pattern)
def get(self, request, *args, **kwargs): try: return super(ResultView, self).get(request, *args, **kwargs) except Http404: messages.add_message(self.request, messages.WARNING, _('Check result does not exist (anymore)')) return HttpResponseRedirect(redirect_to=reverse_lazy( 'django_datawatch_index'))
def _get_obj_does_not_exist_redirect(self, request, opts, object_id): """ Create a message informing the user that the object doesn't exist and return a redirect to the admin index page. """ msg = _("""%(name)s with ID "%(key)s" doesn't exist. Perhaps it was deleted?""") % { 'name': force_text(opts.verbose_name), 'key': unquote(object_id), } self.message_user(request, msg, messages.WARNING) url = reverse('admin:index', current_app=self.admin_site.name) return HttpResponseRedirect(url)
def send(self, request, queryset): msgs = [] sent = 0 errors = 0 for reimb in queryset: try: reimb.send(request.user) msgs.append(emails.create_reimbursement_email(reimb, request)) sent += 1 except ValidationError as e: errors += 1 logging.error(e.message) if msgs: connection = mail.get_connection() connection.send_messages(msgs) if sent > 0 and errors > 0: self.message_user(request, ( "%s reimbursements sent, %s reimbursements not sent. Did you " "check that they were invited before and with money assigned?" % (sent, errors)), level=messages.WARNING) elif sent > 0: self.message_user(request, '%s reimbursement sent' % sent, level=messages.SUCCESS) else: self.message_user(request, 'Reimbursement couldn\'t be sent! Did you check ' 'that app was invited before and with money ' 'assigned?', level=messages.ERROR)
def settings_view(request, pk): server = get_object_or_404(Server, pk=pk, owner=request.user) context = {'server': server} messages.add_message( request, messages.WARNING, "This page is here for preview only. You won't be able to save your changes yet!", extra_tags='danger' ) return render(request, 'autostew_web_account/server_settings.html', context)
def set_installable(self, request, queryset): invalid_ifs_per_host = [] for obj in queryset: invalid_ifs = obj.interface_set.filter(ip4address__isnull=True) if invalid_ifs.exists(): invalid_ifs_per_host.append(self._get_host_warning_message(obj, invalid_ifs)) obj.pxe_installable = True obj.save() # triggers post save signal if invalid_ifs_per_host: self.message_user(request, message='\n'.join(invalid_ifs_per_host), level=messages.WARNING)
def promote_instances(self, request, queryset): """ Promote transmitted PostgreSQL replication instances to master state """ if request.POST.get('post') == 'yes': for inst_id in request.POST.getlist(admin.ACTION_CHECKBOX_NAME): inst = Instance.objects.get(pk=inst_id) try: util = PGUtility(inst) util.promote() except Exception, e: self.message_user(request, "%s : %s" % (e, inst), messages.ERROR) continue self.message_user(request, "%s promoted to read/write!" % inst) return # Now go to the confirmation form. It's very basic, and only serves # to disrupt the process and avoid accidental promotions that would # necessitate a resync. queryset = queryset.exclude(master_id__isnull=True) if queryset.count() < 1: self.message_user(request, "No valid replicas to promte!", messages.WARNING) return return render(request, 'admin/haas/instance/promote.html', {'queryset' : queryset, 'opts': self.model._meta, 'action_checkbox_name': admin.ACTION_CHECKBOX_NAME, } )
def download_spss_labels(request, username, form_id_string): xform = get_object_or_404(XForm, user__username__iexact=username, id_string__exact=form_id_string) owner = User.objects.get(username__iexact=username) helper_auth_helper(request) if not has_permission(xform, owner, request, xform.shared): return HttpResponseForbidden('Not shared.') try: xlsform_io= xform.to_xlsform() if not xlsform_io: messages.add_message(request, messages.WARNING, _(u'No XLS file for your form ' u'<strong>%(id)s</strong>') % {'id': form_id_string}) return HttpResponseRedirect("/%s" % username) except: return HttpResponseServerError('Error retrieving XLSForm.') survey= survey_from.xls(filelike_obj=xlsform_io) zip_filename= '{}_spss_labels.zip'.format(xform.id_string) zip_io= survey_to_spss_label_zip(survey, xform.id_string) response = StreamingHttpResponse(FileWrapper(zip_io), content_type='application/zip; charset=utf-8') response['Content-Disposition'] = 'attachment; filename={}'.format(zip_filename) return response
def enter_data(request, username, id_string): owner = get_object_or_404(User, username__iexact=username) xform = get_object_or_404(XForm, user__username__iexact=username, id_string__exact=id_string) if not has_edit_permission(xform, owner, request, xform.shared): return HttpResponseForbidden(_(u'Not shared.')) form_url = _get_form_url(request, username, settings.ENKETO_PROTOCOL) try: url = enketo_url(form_url, xform.id_string) if not url: return HttpResponseRedirect(reverse('onadata.apps.main.views.show', kwargs={'username': username, 'id_string': id_string})) return HttpResponseRedirect(url) except Exception as e: data = {} owner = User.objects.get(username__iexact=username) data['profile'], created = \ UserProfile.objects.get_or_create(user=owner) data['xform'] = xform data['content_user'] = owner data['form_view'] = True data['message'] = { 'type': 'alert-error', 'text': u"Enketo error, reason: %s" % e} messages.add_message( request, messages.WARNING, _("Enketo error: enketo replied %s") % e, fail_silently=True) return render(request, "profile.html", data) return HttpResponseRedirect(reverse('onadata.apps.main.views.show', kwargs={'username': username, 'id_string': id_string}))
def level2alert(lvl): ''' Translate django.contrib.auth message levels to bootstrap alert classes. ''' tr = { messages.SUCCESS: 'success', messages.WARNING: 'warning', messages.ERROR: 'danger', } return tr.get(lvl, 'info')
def review_nominated_games_view(self, request, object_id): season = get_object_or_404(Season, pk=object_id) if not request.user.has_perm('tournament.review_nominated_games', season.league): raise PermissionDenied selections = GameSelection.objects.filter(season=season).order_by('pairing__teamplayerpairing__board_number') nominations = GameNomination.objects.filter(season=season).order_by('pairing__teamplayerpairing__board_number', 'date_created') selected_links = set((s.game_link for s in selections)) link_counts = {} link_to_nom = {} first_nominations = [] for n in nominations: value = link_counts.get(n.game_link, 0) if value == 0: first_nominations.append(n) link_to_nom[n.game_link] = n link_counts[n.game_link] = value + 1 selections = [(link_counts.get(s.game_link, 0), s, link_to_nom.get(s.game_link, None)) for s in selections] nominations = [(link_counts.get(n.game_link, 0), n) for n in first_nominations if n.game_link not in selected_links] if season.nominations_open: self.message_user(request, 'Nominations are still open. You should edit the season and close nominations before reviewing.', messages.WARNING) context = { 'has_permission': True, 'opts': self.model._meta, 'site_url': '/', 'original': season, 'title': 'Review nominated games', 'selections': selections, 'nominations': nominations, 'is_team': season.league.competitor_type == 'team', } return render(request, 'tournament/admin/review_nominated_games.html', context)
def check(request, id): node = Node.find_by_id(id) client = NodeClient(node.address + ":9000") ok, metrics = client.get_state() if ok: node.update(status="UP", last_update=datetime.datetime.now()) messages.add_message(request, messages.INFO, 'The node was reachable') else: messages.add_message(request, messages.WARNING, 'The node at {} was unreachable'.format(node.address)) node.update(status="DOWN", last_update=datetime.datetime.now()) return HttpResponseRedirect(reverse("nodes:home"))
def metrics(request, id): node = Node.find_by_id(id) if not node or not request.user.administrator: raise PermissionDenied() client = NodeClient(node.address + ":9000") ok, metrics = client.get_state() if not ok: messages.add_message(request, messages.WARNING, 'The node at {} was unreachable'.format(node.address)) return render(request, 'nodes/metrics.html', { "node": node, "metrics": metrics})
def place_bid(request, auc: Auction, bf: BidForm): team = request.team try: auc.place_bid(team, bf.cleaned_data['bid'] * bf.cleaned_data['coef']) winner, offer = auc.effective_offer if winner == team: messages.add_message(request, messages.SUCCESS, "Výborn?! Nyní vyhráváte tuto aukci.") else: messages.add_message(request, messages.WARNING, "Bohužel, byli jste p?ehozeni. Zkuste nabídnout více!") return redirect("detail", auc.id) except AuctionException as e: bf.add_error('bid', str(e))
def dispatch(self, request, *args, **kwargs): if not request.user.is_superuser: messages.add_message( request, messages.WARNING, u'Apenas o administrador tem permissão para realizar esta operação.', 'permission_warning') return redirect('base:index') return super(SuperUserRequiredMixin, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): if not self.check_user_permissions(request): messages.add_message( request, messages.WARNING, u'Usuário não tem permissão para realizar esta operação.', 'permission_warning') return redirect('base:index') return super(CheckPermissionMixin, self).dispatch(request, *args, **kwargs)
def check_user_delete_permission(self, request, object): codename = str(object._meta.app_label) + '.delete_' + \ str(object.__name__.lower()) if not request.user.has_perm(codename): messages.add_message( request, messages.WARNING, u'Usuário não tem permissão para realizar esta operação.', 'permission_warning') return False return True
def login(request): if request.user.is_authenticated(): return redirect('/') if request.method == 'POST': login_form = forms.LoginForm(request.POST) if login_form.is_valid(): login_name=request.POST['username'].strip() login_password=request.POST['password'] user = authenticate(username=login_name, password=login_password) if user is not None: if user.is_active: auth.login(request, user) messages.add_message(request, messages.SUCCESS, 'login successful') return redirect('/') else: messages.add_message(request, messages.WARNING, 'account cant use') else: messages.add_message(request, messages.WARNING, 'login fail') else: messages.add_message(request, messages.INFO,'Please check input content') else: login_form = forms.LoginForm() template = get_template('login.html') request_context = RequestContext(request) request_context.push(locals()) html = template.render(request_context) return HttpResponse(html)
def get_object(self, queryset=None): if len(self.request.user.get_unconfirmed_emails()) > 0: messages.add_message( self.request, messages.WARNING, _('Your newly set email address has not yet been confirmed') ) return self.request.user
def dispatch(self, request, *args, **kwargs): if 'p' in request.GET and 'code' in request.GET: # preserve other query params than p and code when we redirect other_params = request.GET.copy() del other_params['p'] del other_params['code'] url = '{}?{}'.format(request.path, other_params.urlencode(safe='/')) if other_params else request.path user = authenticate(user_pk=request.GET['p'], code=request.GET['code']) # case where user is already authenticated and different from user above ==> redirect with warning message if request.user.is_authenticated and request.user != user: messages.add_message( request=request, level=messages.WARNING, message=self.get_message_string(request.user) ) return HttpResponseRedirect(url) # case where user is being authenticated ==> we show a message but only with info level elif user: login(request, user) messages.add_message( request=request, level=messages.INFO, message=self.get_message_string(user) ) return HttpResponseRedirect(url) elif request.user.is_authenticated: return super().dispatch(request, *args, **kwargs) return redirect_to_login(request.get_full_path(), self.unlogged_redirect_url)
def post(self, request, *args, **kwargs): self.object = self.get_object() self.object.published = False self.object.save() send_cancellation_notification.delay(self.object.pk) messages.add_message( request, messages.WARNING, _("L'événement « {} » a bien été annulé.").format(self.object.name) ) return HttpResponseRedirect(self.success_url)
def form_valid(self, form): _ = super(Register, self).form_valid(form) messages.add_message(self.request, messages.WARNING, '????????????{}?' '?<a href="http://mail.{}">????</a>?????'.format(self.object.email, self.object.email.split('@')[1])) return HttpResponseRedirect(reverse_lazy('login'))
def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated() or not request.user.email_verified: messages.add_message(request, messages.WARNING, '???????') return self.handle_no_permission() return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated() or not getattr(request.user, 'ss_user', None): messages.add_message( request, messages.WARNING, '????<a href="{}">???</a>??Shadowsocks???'.format(reverse_lazy('ss:invite_code_list'))) return self.handle_no_permission() return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
def save_model(self, request, obj, form, change): if not obj.key: obj.key = generate_key() messages.add_message(request, messages.WARNING, ('The API Key for %s is %s. Please note it since you will not be able to see it again.' % (obj.name, obj.key))) obj.save()
def test_message_on_logout(self): """ Message is sent to propose user to logout of CAS. """ r = self.client.post('/accounts/logout/') r_messages = get_messages(r.wsgi_request) expected_msg = Message(messages.WARNING, self.expected_msg_str) self.assertIn(expected_msg, r_messages) self.assertTemplateUsed(r, 'cas_account/messages/logged_out.txt')
def test_message_on_logout(self): message_on_logout = self.provider.message_on_logout(self.request) self.assertTrue(message_on_logout) message_level = self.provider.message_on_logout_level(self.request) self.assertEqual(messages.WARNING, message_level)
def enter_data(request, username, id_string): owner = get_object_or_404(User, username__iexact=username) xform = get_object_or_404(XForm, user__username__iexact=username, id_string__iexact=id_string) if not has_edit_permission(xform, owner, request, xform.shared): return HttpResponseForbidden(_(u'Not shared.')) form_url = _get_form_url(request, username, settings.ENKETO_PROTOCOL) try: url = enketo_url(form_url, xform.id_string) if not url: return HttpResponseRedirect(reverse('formshare.apps.main.views.show', kwargs={'username': username, 'id_string': id_string})) return HttpResponseRedirect(url) except Exception as e: data = {} owner = User.objects.get(username__iexact=username) data['profile'], created = \ UserProfile.objects.get_or_create(user=owner) data['xform'] = xform data['content_user'] = owner data['form_view'] = True data['message'] = { 'type': 'alert-error', 'text': u"Enketo error, reason: %s" % e} messages.add_message( request, messages.WARNING, _("Enketo error: enketo replied %s") % e, fail_silently=True) return render(request, "profile.html", data) return HttpResponseRedirect(reverse('formshare.apps.main.views.show', kwargs={'username': username, 'id_string': id_string}))
def post(self, request, *args, **kwargs): user = self.request.user filter_string = self.request.POST.get('string') delete = self.request.POST.get('delete', 'false') if delete == 'true': # even if the queryset is empty there are no problems Filter.objects.filter(user=user, queryset=filter_string).delete() return HttpResponseRedirect(self.get_success_url()) if filter_string: name = self.request.POST.get('name') if not re.match("^[\w\s,.]+$", name) or len(name) > 99: messages.add_message(request, messages.WARNING, _("""Filter name can only contain letters, numbers, commas or periods. Maximum length is 99 characters""") ) return HttpResponseRedirect(self.get_success_url()[:-10]) typ = self.request.POST.get('typ') check = Filter.objects.filter(user=user, typ=typ, queryset=filter_string) if check.exists(): messages.add_message(request, messages.WARNING, _("You already have a saved filter for that querystring") + ": " + check.first().name) return HttpResponseRedirect(self.get_success_url()) if Filter.objects.filter(user=user, name=name, typ=typ).exists(): messages.add_message(request, messages.WARNING, _("You already have a saved filter with the name") + ": " + name) return HttpResponseRedirect(self.get_success_url()) Filter(user=user, queryset=filter_string, typ=typ, name=name).save() return HttpResponseRedirect(self.get_success_url())
def form_valid(self, form): email = form.cleaned_data['email'] user = get_object_or_404(User, email=email) if user.is_active: messages.add_message( self.request, messages.WARNING, 'Account already active. Please login') return redirect(reverse('user_manager:login')) user_service.send_activation_email(request=self.request, user=user) messages.add_message(self.request, messages.INFO, 'Activation email has been sent.') return redirect('/')
def registrar_usuario(request, **kwargs): if request.method == "POST": form = RegistracionForm(request.POST) if form.is_valid(): #Crear usuario y asignarle atributos usuario = User() usuario.is_active = False usuario.username = form.cleaned_data.get("username") usuario.email = form.cleaned_data["email"].strip().lower() password = form.cleaned_data.get("password1") usuario.set_password(password) usuario.save() # Generar link de activacion key, url_activacion = _generar_link_activacion(request, usuario.email) # Guardar la "confirmacion_key" en el perfil del usuario perfil = PerfilUsuario(usuario=usuario) perfil.confirmacion_key = key perfil.save() # Enviar email de activacion _enviar_mail_activacion(usuario.email, url_activacion) messages.add_message(request, messages.INFO, 'Te hemos enviado un Email de confirmacion.') messages.add_message(request, messages.INFO, url_activacion) return redirect("/") else: if request.user.is_authenticated(): messages.add_message(request, messages.WARNING, 'Ya tenes una cuenta, no te hagas el vivo...') return redirect('/') form = RegistracionForm() return render_to_response("usuarios/registracion.html", RequestContext(request, {'form': form}))
def handle(self): ''' Handles a Add Container request. Adds the specific container to the database :return: a rendered site specific for the request ''' self.form = AddForm(self.request.POST, self.request.FILES) if not self.form.is_valid(): messages.add_message(self.request, messages.ERROR, 'No valid container detected. Maybe your container needs a password?') return self._render_upload_page(form=self.form) try: result = UserCertificateManager.add_keycontainer(self.form._cert_bytes(), self.form._read_password()) for e in result.exceptions: messages.add_message(self.request, messages.WARNING, str(e)) if not result.success: return self._render_upload_page() if result.certificate is not None and result.privatekey is None: result.privatekey = result.certificate.private_key if result.certificate is None and result.privatekey is not None: result.certificate = result.privatekey.certificates.all()[0] return self._render_added_page(result) except (ValueError, TypeError, AsymmetricKeyError, OSError) as e: messages.add_message(self.request, messages.ERROR, "Error reading file. Maybe your file is corrupt?") return self._render_upload_page(form=self.form) except Exception as e: messages.add_message(self.request, messages.ERROR, "Internal error: " + str(e)) return self._render_upload_page(form=self.form)
def post(self, request, club_id, *args, **kwargs): club = Club.objects.get(pk=club_id) budget_form = self.budget_form_class() budget_form.fields['did'].queryset = Division.objects.filter(cid=club) division_form = self.division_form_class if 'division' in request.POST: division_form = self.division_form_class(request.POST) if division_form.is_valid(): division = division_form.save() division.cid = club division.save() messages.add_message(request, messages.SUCCESS, 'You Have Created a New Division!') return HttpResponseRedirect(reverse('suite:budget', args=[club_id])) else: messages.add_message(request, messages.WARNING, 'Cannot Make Division with Same Name') return HttpResponseRedirect(reverse('suite:budget', args=[club_id])) elif 'budget' in request.POST: budget_form = self.budget_form_class(request.POST) if budget_form.is_valid(): budget = budget_form.save(commit=True) budget.save() else: messages.add_message(request, messages.WARNING, 'Could not create budget.') books = self.generate_books(club.division_set.all()) total_budget = 0 total_expense = 0 for book in books: total_budget = total_budget + book['total_budget'] total_expense = total_expense + book['total_expense'] return render(request, self.template_name, { 'books' : books, 'club': club, 'budget_form' : budget_form, 'division_form' : division_form, 'total_budget' : total_budget, 'total_expense' : total_expense})
def save_model(self, request, obj, form, change): """ Automatically detect/populate several fields before saving instance Since we're defining what is (hopefully) an existing structure, we should be able to auto-detect several elements from the database itself. There can also a backend monitor on each server that will keep these values updated, but bootstrapping is always best. Autodetected fields: * is_online * master * version """ # First, check the online status. We want this to be as fresh as # possible, so we might as well grab it now. obj.is_online = False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) check = sock.connect_ex((obj.server.hostname, obj.herd.db_port)) if check == 0: obj.is_online = True # Then, since herds are organized such that each herd follows a single # primary node, we can auto-declare that this is a replica or not. # If we search and find a primary for this herd, that instance will # become our master. util = PGUtility(obj) obj.master = util.get_herd_primary() obj.version = util.get_version() if obj.master and not obj.version: obj.version = obj.master.version # Save now that we've hijacked everything. obj.save() # Attempt to initialize the instance. This only works if the instance # doesn't already exist. It's also optional, so don't derail the save # just because it didn't fully work. try: util.init_missing() except Exception, e: self.message_user(request, "Instance init: %s" % str(e), messages.WARNING )
def share_level(request, id, counter): xf = XForm.objects.get(id_string=id) # sl = dict(request.POST).get('sl')[int(counter)-1] sl = request.POST.get('sl') if not FieldSightFormLibrary.objects.filter(xf__id_string=id).exists(): form = FieldSightFormLibrary() form.xf= xf else: form = FieldSightFormLibrary.objects.get(xf__id_string=id) if not sl: if form.pk: form.delete() messages.add_message(request, messages.WARNING, '{0} Form Shared Removed'.format(xf.title)) else: if sl == '0': form.is_global = True form.organization = None form.project = None form.save() messages.add_message(request, messages.INFO, '{0} Shared Globally '.format(xf.title)) elif sl == '1': form.is_global = False if hasattr(request,"project") and request.project: form.organization = request.project.organization form.project = None form.save() messages.add_message(request, messages.INFO, '{0} Shared To Organization Level'.format(xf.title)) elif hasattr(request,"organization") and request.organization: form.organization = request.organization form.project = None form.save() messages.add_message(request, messages.INFO, '{0} Shared To Organization Level'.format(xf.title)) else: messages.add_message(request, messages.WARNING, '{0} Not Shared. You Cannot Share to Organization Level'. format(xf.title)) elif sl == '2': if hasattr(request,"project") and request.project: form.is_global = False form.organization = None form.project = request.project form.save() messages.add_message(request, messages.INFO, '{0} Shared to Project Level '.format(xf.title)) else: messages.add_message(request, messages.WARNING, '{0} Form Not Shared. You Cannot Share to Project Level' .format(xf.title)) return HttpResponseRedirect(reverse('forms:forms-list'))
def edit_share_stages(request, id): fgroup = get_object_or_404( FormGroup, pk=id) if request.method == 'POST': form = GroupEditForm(data=request.POST,instance=fgroup) if form.is_valid(): group = form.save() sl = form.data['sl'] if sl == '': group.is_global=False group.organization=None group.project=None group.save() if sl == '0': group.is_global= True group.organization=None group.project=None group.save() elif sl == '1': group.is_global = False if hasattr(request,"project") and request.project: group.organization = request.project.organization group.project = None group.save() messages.add_message(request, messages.INFO, '{0} Shared To Organization Level'.format(group.name)) elif hasattr(request,"organization") and request.organization: group.organization = request.organization group.project = None group.save() messages.add_message(request, messages.INFO, '{0} Shared To Organization Level'.format(group.name)) else: messages.add_message(request, messages.WARNING, '{0} Not Shared. You Cannot Share to Organization Level'. format(group.name)) elif sl == '2': if hasattr(request,"project") and request.project: group.is_global = False group.organization = None group.project = request.project group.save() messages.add_message(request, messages.INFO, '{0} Shared to Project Level '.format(group.name)) else: messages.add_message(request, messages.WARNING, '{0} Form Not Shared. You Cannot Share to Project Level' .format(group.name)) return HttpResponseRedirect(reverse("forms:group-list")) sl = '' if fgroup.is_global: sl = 0 elif fgroup.project: sl = 2 elif fgroup.organization: sl = 1 fgroup.shared_level = sl form = GroupEditForm(instance=fgroup) return render(request, "fsforms/edit_formgroup_form.html", {'form': form,'shared':sl})
def download_xlsform(request, username, id_string): xform = get_object_or_404(XForm, user__username__iexact=username, id_string__exact=id_string) owner = User.objects.get(username__iexact=username) helper_auth_helper(request) if not has_permission(xform, owner, request, xform.shared): return HttpResponseForbidden('Not shared.') file_path = xform.xls.name default_storage = get_storage_class()() if file_path != '' and default_storage.exists(file_path): audit = { "xform": xform.id_string } audit_log( Actions.FORM_XLS_DOWNLOADED, request.user, xform.user, _("Downloaded XLS file for form '%(id_string)s'.") % { "id_string": xform.id_string }, audit, request) if file_path.endswith('.csv'): with default_storage.open(file_path) as ff: xls_io = convert_csv_to_xls(ff.read()) response = StreamingHttpResponse( xls_io, content_type='application/vnd.ms-excel; charset=utf-8') response[ 'Content-Disposition'] = 'attachment; filename=%s.xls' % xform.id_string return response split_path = file_path.split(os.extsep) extension = 'xls' if len(split_path) > 1: extension = split_path[len(split_path) - 1] response = response_with_mimetype_and_name( 'vnd.ms-excel', id_string, show_date=False, extension=extension, file_path=file_path) return response else: messages.add_message(request, messages.WARNING, _(u'No XLS file for your form ' u'<strong>%(id)s</strong>') % {'id': id_string}) return HttpResponseRedirect("/%s" % username)
def generate_pairings_view(self, request, object_id): round_ = get_object_or_404(Round, pk=object_id) if not request.user.has_perm('tournament.generate_pairings', round_.season.league): raise PermissionDenied if request.method == 'POST': form = forms.GeneratePairingsForm(request.POST) if form.is_valid(): try: if form.cleaned_data['run_in_background']: signals.do_generate_pairings.send(sender=self.__class__, round_id=round_.pk, overwrite=form.cleaned_data['overwrite_existing']) self.message_user(request, 'Generating pairings in background.', messages.INFO) return redirect('admin:review_pairings', object_id) else: pairinggen.generate_pairings(round_, overwrite=form.cleaned_data['overwrite_existing']) with reversion.create_revision(): reversion.set_user(request.user) reversion.set_comment('Generated pairings.') round_.publish_pairings = False round_.save() self.message_user(request, 'Pairings generated.', messages.INFO) return redirect('admin:review_pairings', object_id) except pairinggen.PairingsExistException: if not round_.publish_pairings: self.message_user(request, 'Unpublished pairings already exist.', messages.WARNING) return redirect('admin:review_pairings', object_id) self.message_user(request, 'Pairings already exist for the selected round.', messages.ERROR) except pairinggen.PairingHasResultException: self.message_user(request, 'Pairings with results can\'t be overwritten.', messages.ERROR) except pairinggen.PairingGenerationException as e: self.message_user(request, 'Error generating pairings. %s' % e.message, messages.ERROR) return redirect('admin:generate_pairings', object_id=round_.pk) else: form = forms.GeneratePairingsForm() context = { 'has_permission': True, 'opts': self.model._meta, 'site_url': '/', 'original': round_, 'title': 'Generate pairings', 'form': form } return render(request, 'tournament/admin/generate_pairings.html', context)