def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
"""
if not isinstance(level, int):
# attempt to get the level if passed a string
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join('`%s`' % l for l in levels)
raise ValueError('Bad message level string: `%s`. '
'Possible values are: %s' % (level, levels_repr))
messages.add_message(request, level, message, extra_tags=extra_tags,
fail_silently=fail_silently)
python类INFO的实例源码
def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
"""
if not isinstance(level, int):
# attempt to get the level if passed a string
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join('`%s`' % l for l in levels)
raise ValueError(
'Bad message level string: `%s`. Possible values are: %s'
% (level, levels_repr)
)
messages.add_message(request, level, message, extra_tags=extra_tags, fail_silently=fail_silently)
def alter_profile(request, username=None):
if username:
the_user = get_object_or_404(User, username__exact=username)
else:
the_user = request.user
if request.method == 'POST':
redirect_url = reverse("view-profile-user", args=[the_user.username])
form = UserAlterDetailsForm(request.POST)
if "cancel" in form.data: # has to be tested before data is cleaned
return HttpResponseRedirect(redirect_url)
assert form.is_valid()
if form.is_valid():
for key in form.cleaned_data:
setattr(the_user, key, form.cleaned_data[key])
the_user.save()
msg = "Profile details changed"
messages.add_message(request, messages.INFO, msg)
return HttpResponseRedirect(redirect_url)
else:
# form = UserAlterDetailsForm(initial=the_user.__dict__)
form = UserAlterDetailsForm(instance=the_user)
return render_template(request, "profiles/alter_profile.html",
{"the_user": the_user,
"form": form})
def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
"""
if not isinstance(level, int):
# attempt to get the level if passed a string
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join('`%s`' % l for l in levels)
raise ValueError(
'Bad message level string: `%s`. Possible values are: %s'
% (level, levels_repr)
)
messages.add_message(request, level, message, extra_tags=extra_tags, fail_silently=fail_silently)
def register(request):
check = User.objects.validateUser(request.POST)
if request.method != 'POST':
return redirect('/')
if check[0] == False:
for error in check[1]:
messages.add_message(request, messages.INFO, error, extra_tags="registration")
return redirect('/')
if check[0] == True:
#has password
hashed_pw = bcrypt.hashpw(request.POST.get('password').encode(), bcrypt.gensalt())
#create user
user = User.objects.create(
first_name = request.POST.get('first_name'),
last_name = request.POST.get('last_name'),
email = request.POST.get('email'),
password = hashed_pw,
)
#add user to session, logging them in
request.session['user_id'] = user.id
#route to user profile page
return redirect('/user')
def edit_timeline(request, slug, template_name="package/timeline_form.html"):
project = get_object_or_404(Project, slug=slug)
if not request.user.profile.can_edit_package(project):
return HttpResponseForbidden("permission denied")
if request.POST:
formset = TimelineEventFormSet(data=request.POST, project=project,)
else:
formset = TimelineEventFormSet(project=project, queryset=TimelineEvent.objects.filter(project=project))
if formset.is_valid():
formset.save()
messages.add_message(request, messages.INFO, 'Project updated successfully')
return HttpResponseRedirect(reverse("package", kwargs={"slug": project.slug}))
return render(request, template_name, {
"formset": formset,
"package": project,
"action": "Save",
})
def edit_images(request, slug, template_name="package/images_form.html"):
project = get_object_or_404(Project, slug=slug)
if not request.user.profile.can_edit_package(project):
return HttpResponseForbidden("permission denied")
if request.POST:
formset = ProjectImagesFormSet(data=request.POST, files=request.FILES, project=project,)
else:
formset = ProjectImagesFormSet(project=project, queryset=ProjectImage.objects.filter(project=project))
if formset.is_valid():
formset.save()
messages.add_message(request, messages.INFO, 'Project updated successfully')
return HttpResponseRedirect(reverse("package", kwargs={"slug": project.slug}))
return render(request, template_name, {
"formset": formset,
"package": project,
"action": "Save",
})
def edit_grid(request, slug, template_name="grid/update_grid.html"):
"""View to modify the grid, handles GET and POST requests.
This view requires user to be logged in.
Template context:
* ``form`` - instance of :class:`grid.forms.GridForm`
"""
if not request.user.profile.can_edit_grid:
return HttpResponseForbidden("permission denied")
grid = get_object_or_404(Grid, slug=slug)
form = GridForm(request.POST or None, instance=grid)
if form.is_valid():
grid = form.save()
message = "Grid has been edited"
messages.add_message(request, messages.INFO, message)
return HttpResponseRedirect(reverse('grid', kwargs={'slug': grid.slug}))
return render(request, template_name, {'form': form, 'grid': grid})
def post(self, request, pk):
email_type = request.POST.get('type', '').lower()
email_obj = Email.objects.get(pk=pk)
if email_type == 'preview':
send_email_obj(email_obj=email_obj, preview=True)
m = 'Preview email has been sent!'
else:
email_obj.recipients = get_subscriber_emails(email_obj=email_obj)
m = 'Email has been sent!'
send_email_obj(email_obj=email_obj)
email_obj.is_sent = True
email_obj.targetted_users = len(email_obj.recipients)
email_obj.save()
messages.add_message(request, messages.INFO, m)
return redirect(reverse(
'admin:emails_email_change', args=(email_obj.id,)))
def post(self, request, club_id, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
reason = form.cleaned_data.get('reason')
club = Club.objects.get(pk=club_id)
messages.add_message(request, messages.INFO, 'Your request has been sent! It is pending review.')
if request.user not in club.members.all():
if JoinRequest.objects.filter(cid=club, uid=request.user).count() <= 0:
join_request = JoinRequest(cid=club, uid=request.user, reason=reason)
join_request.save()
redir = reverse('suite:club_view', args=[club_id])
return HttpResponseRedirect(redir)
return render(request, self.template_name, { 'form' : form })
def server_del(request):
"""
:param request:
:return:
"""
response_data = {}
code = 1
server_id = request.GET.get('server_id')
if server_id != '':
ops_server = OpsServer()
code, msg = ops_server.delete(server_id)
else:
msg = '????, server_id??'
messages.add_message(request, messages.INFO, msg)
# process_logs
response_data['code'] = code
return HttpResponse(json.dumps(response_data), content_type="application/json")
def addcard(request):
if request.method == 'POST':
token = request.POST['stripe_token[id]']
user_profile = UserProfile.objects.get(user=request.user)
network = user_profile.network
if network.update_card(token):
messages.add_message(request, messages.INFO, "addcard_saved",
extra_tags="billing_resp_code")
return redirect("/dashboard/billing")
else:
# The card has been declined
messages.add_message(request, messages.ERROR,
"addcard_stripe_declined", extra_tags="billing_resp_code")
return redirect("/dashboard/billing")
else:
return HttpResponseBadRequest()
def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
"""
if not isinstance(level, int):
# attempt to get the level if passed a string
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join('`%s`' % l for l in levels)
raise ValueError(
'Bad message level string: `%s`. Possible values are: %s'
% (level, levels_repr)
)
messages.add_message(request, level, message, extra_tags=extra_tags, fail_silently=fail_silently)
def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
"""
if not isinstance(level, int):
# attempt to get the level if passed a string
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join('`%s`' % l for l in levels)
raise ValueError('Bad message level string: `%s`. '
'Possible values are: %s' % (level, levels_repr))
messages.add_message(request, level, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def export(self, request, queryset):
"""
Download selected photos as ZIP
"""
zip_subdir = 'photos'
zip_filename = '{}.zip'.format(zip_subdir)
zip_file = os.path.join(settings.MEDIA_ROOT, PHOTOLOGUE_DIR,
zip_filename)
try:
os.remove(zip_file)
except OSError:
pass
with zipfile.ZipFile(zip_file, "a") as zf:
for photo in queryset.all():
path = photo.image.path
if os.path.isfile(path):
fdir, fname = os.path.split(path)
zip_path = os.path.join(zip_subdir, fname)
zf.write(path, zip_path)
link = 'Photos download link: <a href="{0}?v={1}">{0}</a>'.format(
urllib.parse.urljoin(settings.MEDIA_URL,
PHOTOLOGUE_DIR + '/' + zip_filename), time())
messages.add_message(request, messages.INFO, mark_safe(link))
def contact(request):
if request.method == 'POST':
form = ContactView(request.POST)
if form.is_valid():
our_form = form.save(commit=False)
our_form.save()
messages.add_message(
request, messages.INFO,
'Your message has been sent. Thank you.'
)
return HttpResponseRedirect('/')
else:
form = ContactView()
t = loader.get_template('contact/contact.html')
c = RequestContext(request, {'form': form, })
return HttpResponse(t.render(c))
def stage_add_form(request, pk=None):
stage = get_object_or_404(
Stage, pk=pk)
if stage.stage.site:
instance = FieldSightXF(site=stage.stage.site, is_staged=True, is_scheduled=False, stage=stage)
if request.method == 'POST':
form = AssignFormToStageForm(request.POST, instance=instance)
if form.is_valid():
form.save()
messages.add_message(request, messages.INFO, 'Form Assigned Successfully.')
return HttpResponseRedirect(reverse("forms:stages-detail", kwargs={'pk': stage.stage.id}))
else:
form = AssignFormToStageForm(instance=instance)
return render(request, "fsforms/stage_add_form.html", {'form': form, 'obj': stage})
else:
if request.method == 'POST':
form = AssignFormToStageForm(request.POST)
if form.is_valid():
form.save()
messages.add_message(request, messages.INFO, 'Form Assigned Successfully.')
return HttpResponseRedirect(reverse("forms:stages-detail", kwargs={'pk': stage.stage.id}))
else:
form = AssignFormToStageForm()
return render(request, "fsforms/stage_add_form.html", {'form': form, 'obj': stage})
def add_proj_manager(request, pk):
obj = get_object_or_404(
Project, pk=pk)
group = Group.objects.get(name__exact="Project Manager")
role_obj = UserRole(project=obj, group=group)
scenario = 'Assign'
if request.method == 'POST':
form = SetProjectManagerForm(data=request.POST, instance=role_obj, request=request)
if form.is_valid():
role_obj = form.save(commit=False)
user_id = request.POST.get('user')
role_obj.user_id = int(user_id)
role_obj.save()
messages.add_message(request, messages.INFO, 'Project Manager Added')
return HttpResponseRedirect(reverse("fieldsight:project-dashboard", kwargs={'pk': obj.pk}))
else:
form = SetProjectManagerForm(instance=role_obj, request=request)
return render(request, "fieldsight/add_project_manager.html", {'obj':obj,'form':form, 'scenario':scenario})
def add_supervisor(request, pk):
obj = get_object_or_404(
Site, pk=int(pk))
group = Group.objects.get(name__exact="Site Supervisor")
role_obj = UserRole(site=obj, group=group)
if request.method == 'POST':
form = SetSupervisorForm(data=request.POST, instance=role_obj, request=request)
if form.is_valid():
role_obj = form.save(commit=False)
user_id = request.POST.get('user')
role_obj.user_id = int(user_id)
role_obj.save()
messages.add_message(request, messages.INFO, 'Site Supervisor Added')
return HttpResponseRedirect(reverse("fieldsight:site-dashboard", kwargs={'pk': obj.pk}))
else:
form = SetSupervisorForm(instance=role_obj, request=request)
return render(request, "fieldsight/add_supervisor.html", {'obj':obj,'form':form})
def add_central_engineer(request, pk):
obj = get_object_or_404(
Project, pk=pk)
group = Group.objects.get(name__exact="Reivewer")
role_obj = UserRole(project=obj, group=group)
scenario = 'Assign'
if request.method == 'POST':
form = SetProjectRoleForm(data=request.POST, instance=role_obj, request=request)
if form.is_valid():
role_obj = form.save(commit=False)
user_id = request.POST.get('user')
role_obj.user_id = int(user_id)
role_obj.save()
messages.add_message(request, messages.INFO, 'Reviewer Added')
return HttpResponseRedirect(reverse("fieldsight:project-dashboard", kwargs={'pk': obj.pk}))
else:
form = SetProjectRoleForm(instance=role_obj, request=request,)
return render(request, "fieldsight/add_central_engineer.html", {'obj':obj,'form':form, 'scenario':scenario})
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 approve(self, request, queryset):
if not request.user.has_perm('tournament.invite_to_slack'):
self.message_user(request, 'You don\'t have permissions to invite users to slack.', messages.ERROR)
return redirect('admin:tournament_registration_changelist')
count = 0
for reg in queryset:
if reg.status == 'pending' and reg.validation_ok and not reg.validation_warning:
workflow = ApproveRegistrationWorkflow(reg)
send_confirm_email = workflow.default_send_confirm_email
invite_to_slack = workflow.default_invite_to_slack
default_section = workflow.default_section
if workflow.is_late:
retroactive_byes = workflow.default_byes
late_join_points = workflow.default_ljp
else:
retroactive_byes = None
late_join_points = None
workflow.approve_reg(request, None, send_confirm_email, invite_to_slack, default_section, retroactive_byes, late_join_points)
count += 1
self.message_user(request, '%d approved.' % count, messages.INFO)
return redirect('admin:tournament_registration_changelist')
def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
"""
if not isinstance(level, int):
# attempt to get the level if passed a string
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join('`%s`' % l for l in levels)
raise ValueError('Bad message level string: `%s`. '
'Possible values are: %s' % (level, levels_repr))
messages.add_message(request, level, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
"""
if not isinstance(level, int):
# attempt to get the level if passed a string
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join('`%s`' % l for l in levels)
raise ValueError('Bad message level string: `%s`. '
'Possible values are: %s' % (level, levels_repr))
messages.add_message(request, level, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
"""
if not isinstance(level, int):
# attempt to get the level if passed a string
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join('`%s`' % l for l in levels)
raise ValueError('Bad message level string: `%s`. '
'Possible values are: %s' % (level, levels_repr))
messages.add_message(request, level, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def app_edit(request):
if request.method == 'POST':
msg = '????'
form = AppEditForm(request.POST)
if form.is_valid() and App.objects.filter(app_id=form.cleaned_data['app_id']):
f = form.save(commit=False)
f.app_id = form.cleaned_data['app_id']
f.app_key = App.objects.get(pk=form.cleaned_data['app_id']).app_key
f.save()
else:
msg = '??????????!'
messages.add_message(request, messages.INFO, msg)
return HttpResponseRedirect(reverse('app:app_list'))
else:
messages.add_message(request, messages.ERROR, '??????')
return HttpResponseRedirect(reverse('app:app_list'))
def policy_rule_edit(request, policy_id):
if request.method == 'POST':
msg = '????'
form = PolicyRuleEditForm(request.POST)
if form.is_valid():
if PolicyRule.objects.filter(rule_id=form.cleaned_data["rule_id"]):
f = form.save(commit=False)
f.rule_id = form.cleaned_data["rule_id"]
f.save()
else:
msg = '?????!'
messages.add_message(request, messages.INFO, msg)
else:
msg = 'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors))
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect(reverse('policy:policy_rule_list', args=[policy_id]))
else:
messages.add_message(request, messages.ERROR, '?????')
return HttpResponseRedirect(reverse('policy:policy_rule_list', args=[policy_id]))
def _action_send(self, request, *args, **kwargs):
email = request.POST["email"]
try:
email_address = EmailAddress.objects.get(
user=request.user,
email=email,
)
get_adapter(request).add_message(
request,
messages.INFO,
'account/messages/'
'email_confirmation_sent.txt',
{'email': email})
email_address.send_confirmation(request)
return HttpResponseRedirect(self.get_success_url())
except EmailAddress.DoesNotExist:
pass
def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
"""
if not isinstance(level, int):
# attempt to get the level if passed a string
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join('`%s`' % l for l in levels)
raise ValueError('Bad message level string: `%s`. '
'Possible values are: %s' % (level, levels_repr))
messages.add_message(request, level, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def delete_collection(request, path):
"delete_coll"
coll = Collection.find(path)
if not coll:
raise Http404
if not coll.user_can(request.user, "delete"):
raise PermissionDenied
if request.method == "POST":
parent_coll = Collection.find(coll.path)
if parent_coll:
parent_path = parent_coll.container
else:
# Just in case
parent_path = ''
Collection.delete_all(coll.path, username=request.user.name)
messages.add_message(request, messages.INFO,
u"The collection '{}' has been deleted".format(coll.name))
return redirect('archive:view', path=parent_path)
return render(request, 'archive/delete.html', {'collection': coll})