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
python类WARNING的实例源码
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 _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 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)