def change_event(modeladmin, request, queryset):
event_pk = request.POST['event']
try:
event = Event.objects.get(pk=event_pk)
except Event.DoesNotExist:
modeladmin.message_user(
request,
"Could not find event with pk {event_pk}".format(
event_pk=event_pk
),
messages.ERROR,
)
return
queryset.update(event=event)
modeladmin.message_user(
request,
"Added event {event} for {n} quotes".format(
event=event.name,
n=queryset.count(),
),
messages.SUCCESS,
)
python类ERROR的实例源码
def login_view(request):
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
messages.add_message(request, messages.SUCCESS, "Login successful.", extra_tags='success')
return redirect('account:home')
else:
messages.add_message(request, messages.ERROR, "You account is disabled.", extra_tags='danger')
return redirect('account:login')
else:
messages.add_message(request, messages.ERROR, "Your username and/or your password is incorrect.", extra_tags='warning')
return redirect('account:login')
else:
if request.user.is_authenticated():
return redirect('account:home')
else:
return render(request, 'autostew_web_account/login.html')
def post(self, request, *args, **kwargs):
if not request.user.has_perm('file.manage_resources'):
raise PermissionDenied
parent = self._get_folder()
form = ResourceFolderForm(folder=parent, data=self.request.POST)
folder = ResourceFolder.objects.filter(parent=parent, name=form.data['name']).first()
if folder is not None:
messages.add_message(request, messages.ERROR, 'Un dossier existe déjà avec ce nom')
else:
folder = ResourceFolder.objects.create(
name=form.data['name'],
parent=parent
)
messages.add_message(request, messages.SUCCESS, 'Dossier créé')
return redirect(reverse('resource-folder-list', kwargs={'folder_pk': folder.id}))
def post(self, request, *args, **kwargs):
if 'resign' in request.POST:
club = Club.objects.get(id=request.POST['club_id'])
if club.remove_member(request.user, request.user):
messages.add_message(request, messages.SUCCESS,
'Successfully resigned from %s.' % club.club_name)
else:
messages.add_message(request, messages.ERROR,
'Could not resign from %s.' % club.club_name)
elif 'disband' in request.POST:
club = Club.objects.get(id=request.POST['club_id'])
club._clear_permissions()
club.delete()
messages.add_message(request, messages.SUCCESS,
'Sucessfully disbanded %s.' % club.club_name)
clubs = request.user.get_clubs()
return render(request, self.template_name, {'clubs' : clubs})
def post(self, request, club_id, *args, **kwargs):
club = Club.objects.get(pk=club_id)
old_club_name = club.club_name
form = self.form_class(instance=club)
if 'edit' in request.POST:
form = self.form_class(request.POST, request.FILES, instance=club)
if form.is_valid():
club.update_group_names(old_club_name)
club = form.save()
return HttpResponseRedirect(reverse('suite:club_manage'))
else:
messages.add_message(request, messages.ERROR, 'Could not make changes to your club.')
return render(request, self.template_name, { 'form' : form, 'club' : club })
def post(self, request, club_id, event_id, *args, **kwargs):
club = suite.models.Club.objects.get(pk=club_id)
event = suite.models.Event.objects.get(pk=event_id)
form = self.form_class(instance=event)
if 'edit' in request.POST:
form = self.form_class(request.POST, request.FILES, instance=event)
if form.is_valid():
event = form.save()
#print('valid')
messages.add_message(request, messages.SUCCESS, 'Successfully edited event.')
return HttpResponseRedirect(reverse('suite:club_view',
kwargs={'club_id': club.id }))
else:
messages.add_message(request, messages.ERROR, 'Could not make changes to your event.')
return render(request, self.template_name, { 'form' : form,
'club' : club,
'event' : event})
def post(self, request, club_id, *args, **kwargs):
club = get_object_or_404(Club, pk=club_id)
if 'delete' in request.POST:
user_id = request.POST['delete']
if not club.remove_member(request.user, User.objects.get(id=user_id)):
messages.add_message(request, messages.ERROR, 'Cannot delete Yourself!')
elif 'promote' in request.POST:
user_id = request.POST['promote']
act_on_user = User.objects.get(id=user_id)
if not club.is_officer(act_on_user):
club.promote_to_officer(request.user, act_on_user)
elif club.is_officer(act_on_user):
club.promote_officer_to_owner(request.user, act_on_user)
elif 'demote' in request.POST:
user_id = request.POST['demote']
act_on_user = User.objects.get(id=user_id)
if club.is_owner(act_on_user):
if not club.demote_owner_to_officer(request.user, act_on_user):
messages.add_message(request, messages.ERROR, 'You Cannot Demote Yourself!')
elif club.is_officer(act_on_user):
club.demote_from_officer(request.user, act_on_user)
members = self.get_members(club)
return render(request, self.template_name, {'club': club, 'members' : members})
def post(self, request):
if 'details' in request.POST:
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
else:
messages.add_message(request, messages.ERROR, 'Could not edit account details.')
form2 = PasswordChangeForm(user=request.user)
args = {'form': form, 'form2': form2 }
return render(request, 'account.html', args)
elif 'password' in request.POST:
form2 = PasswordChangeForm(user=request.user, data=request.POST)
if form2.is_valid():
form2.save()
update_session_auth_hash(request, form2.user)
messages.add_message(request, messages.SUCCESS, 'Sucessfully changed password.')
else:
messages.add_message(request, messages.ERROR, 'Password change unsuccessful.')
form = EditProfileForm(instance=request.user)
args = {'form': form, 'form2': form2 }
return render(request, 'account.html', args)
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 restart_instances(self, request, queryset):
"""
Restart all transmitted PostgreSQL instances
Basicaly we just call for a fast stop followed by a start. Nothing
complicated here. Unlike stop, we don't skip stopped instances, and
unline start, we don't skip running ones.
"""
for inst in queryset:
try:
util = PGUtility(inst)
util.stop()
util.start()
except Exception, e:
self.message_user(request, "%s : %s" % (e, inst), messages.ERROR)
continue
self.message_user(request, "%s restarted!" % inst)
def reload_instances(self, request, queryset):
"""
Reload all transmitted PostgreSQL instances
This is provided as a way of reloading configuration files.
"""
for inst in queryset:
try:
util = PGUtility(inst)
util.reload()
except Exception, e:
self.message_user(request, "%s : %s" % (e, inst), messages.ERROR)
continue
self.message_user(request, "%s config files reloaded!" % inst)
def server_edit(request):
msg = ''
ftp_id = request.REQUEST.get('id', '')
if request.method == 'POST':
ftp_name = request.REQUEST.get('ftp_name', '')
server_id = request.REQUEST.get('server_id', '')
ftp_port = request.REQUEST.get('ftp_port', '')
ftp_description = request.REQUEST.get('ftp_description', '')
ovs = OpsFtpServer(request.user)
res, msg = ovs.server_edit(ftp_id, ftp_name, server_id, ftp_port, ftp_description)
if res:
messages.add_message(request, messages.SUCCESS, 'FTP??????????????????????')
return HttpResponseRedirect('/pureftp/s/list/')
if ftp_id:
data = FtpServer.objects.get(pk=ftp_id)
server_list = Server.objects.all()
return render_to_response('pureftp/s_edit.html',
{'msg': msg, 'data': data, 'server_list': server_list},
context_instance=RequestContext(request))
else:
messages.add_message(request, messages.ERROR, '???????????????????')
return HttpResponseRedirect('/pureftp/s/list/')
def server_del(request):
"""
:param request:
:return:
"""
vpn_id = request.REQUEST.get('id', '')
if vpn_id:
ftp_server_info = FtpServer.objects.get(pk=vpn_id)
account_num = FtpAccount.objects.filter(ftp_server=ftp_server_info).count()
if account_num < 1:
msg = 'FTP????????'
FtpServer.objects.get(pk=vpn_id).delete()
messages.add_message(request, messages.SUCCESS, msg)
else:
msg = '?????FTP????ERROR: ??SERVER?????????????????????????IP?'
messages.add_message(request, messages.ERROR, msg)
else:
msg = 'ID?????????'
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect("/pureftp/s/list/")
def group_edit(request):
if request.method == 'POST':
# form = GroupEditForm(request.POST)
# if form.is_valid():
# cd = form.cleaned_data
ops_server = OpsGroup(request.user)
res, msg = ops_server.group_edit(request.POST)
if res:
messages.add_message(request, messages.SUCCESS, msg)
else:
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect('/system/g/list/')
else:
gid = request.REQUEST.get('gid', '')
data = Group.objects.get(pk=gid)
group_perms = data.permissions.all()
all_perms = Permission.objects.all()
return render_to_response('system/group_edit.html',
{'data': data, 'group_perms': group_perms,
'all_perms': all_perms})
def permit_add(request):
"""
????
:param request:
:return:
"""
if request.method == 'POST':
ops_permit = OpsPermit(request.user)
res, msg = ops_permit.permit_add(request.POST)
page = int(request.REQUEST.get('page', 1))
if res:
messages.add_message(request, messages.SUCCESS, msg)
else:
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect('/system/p/list/?page=' + str(page))
else:
content_type_list = ContentType.objects.all()
return render_to_response('system/permit_add.html', {'content_type_list': content_type_list},
context_instance=RequestContext(request))
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 form_valid(self, form):
#add the dates to the existing data in the sessions
notice = form.save(commit=False)
serializer = NoticeSerializer(notice)
session_data = self.request.session['new-notice']
session_data['starts_at'] = serializer.data['starts_at']
session_data['ends_at'] = serializer.data['ends_at']
session_data['timezone'] = serializer.data['timezone']
#save
serializer = NoticeSerializer(data=session_data)
if serializer.is_valid():
notice = serializer.save(user=self.request.user)
messages.add_message(self.request, messages.SUCCESS, 'Your notice has been posted')
return redirect(notice)
else:
messages.add_message(self.request, messages.ERROR, 'Sorry, something went wrong')
def create_slack_channels(self, request, queryset):
team_ids = []
skipped = 0
for team in queryset.select_related('season').nocache():
if not team.season.is_active or team.season.is_completed:
self.message_user(request, 'The team season must be active and not completed in order to create channels.', messages.ERROR)
return
if len(team.season.tag) > 3:
self.message_user(request, 'The team season tag is too long to create a channel.', messages.ERROR)
return
if team.slack_channel == '':
team_ids.append(team.pk)
else:
skipped += 1
signals.do_create_team_channel.send(sender=self, team_ids=team_ids)
self.message_user(request, 'Creating %d channels. %d skipped.' % (len(team_ids), skipped), 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 app_add(request):
if request.method == 'POST':
form = AppAddForm(request.POST)
if form.is_valid():
if not App.objects.filter(app_domain=form.cleaned_data['app_name']):
f = form.save(commit=False)
f.app_key = random_str()
f.save()
messages.add_message(request, messages.SUCCESS, '??????')
return HttpResponseRedirect(reverse('app:app_list'))
messages.add_message(request, messages.ERROR, '???????????????')
messages.add_message(request, messages.ERROR, 'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors)))
return HttpResponseRedirect(reverse('app:app_add'))
else:
data = Policy.objects.all()
return render_to_response('app/list.html', {'data': data}, context_instance=RequestContext(request))
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 user_otp(request, uid):
msg = 'OTP?????'
try:
data = User.objects.get(pk=uid)
profile = UserProfile.objects.get(user=data)
profile.otp = pyotp.random_base32()
profile.save()
messages.add_message(request, messages.SUCCESS, msg)
return HttpResponseRedirect(reverse('system:system_user_list'))
except User.DoesNotExist:
msg = '??????'
except UserProfile.DoesNotExist:
msg = '???????!'
UserProfile(user=data, otp=pyotp.random_base32(), avatar='').save()
except Exception, e:
msg = '????: ' + e.message
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect(reverse('system:system_user_list'))
def group_add(request):
if request.method == 'POST':
name = request.POST.get('name')
permission = request.POST.getlist('permission')
try:
Group.objects.get(name=name)
res, msg = False, 'GroupIsExists!'
except Group.DoesNotExist:
g = Group(name=name)
g.permissions = permission
g.save()
# for p in permission:
# g.permissions.add(p)
res, msg = True, 'Create Success!'
if res:
messages.add_message(request, messages.SUCCESS, msg)
else:
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect(reverse('system:system_group_list'))
else:
data = Permission.objects.all()
return render_to_response('system/group_create.html',
{'data': data}, context_instance=RequestContext(request))
def group_edit(request, gid):
if request.method == 'POST':
gid = request.POST.get('gid')
name = request.POST.get('name')
permission = request.POST.getlist('permission')
try:
g = Group.objects.get(pk=gid)
g.name = name
g.permissions = permission
g.save()
res, msg = True, 'role?edit success?'
except User.DoesNotExist:
res, msg = False, 'role?not exists?'
if res:
messages.add_message(request, messages.SUCCESS, msg)
else:
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect(reverse('system:system_group_list'))
else:
data = Group.objects.get(pk=gid)
group_perms = data.permissions.all()
all_perms = Permission.objects.all()
return render_to_response('system/group_edit.html',
{'data': data, 'group_perms': group_perms,
'all_perms': all_perms}, context_instance=RequestContext(request))
def permit_edit(request, pid):
if request.method == 'POST':
pid = request.POST.get('id')
name = request.POST.get('name')
try:
g = Permission.objects.get(pk=pid)
g.name = name
g.save()
res, msg = True, 'Success!'
except Permission.DoesNotExist:
res, msg = False, 'PermissionNotExists!'
if res:
messages.add_message(request, messages.SUCCESS, msg)
else:
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect(reverse('system:system_permit_list'))
else:
data = Permission.objects.get(pk=pid)
content_type_list = ContentType.objects.all()
return render_to_response('system/permit_edit.html', {'data': data, 'content_type_list': content_type_list},
context_instance=RequestContext(request))
def permit_delete(request, pid):
"""
????
:param pid:
:param request:
:return:
"""
page = int(request.REQUEST.get('page', 1))
try:
Permission.objects.get(pk=pid).delete()
msg = '???????codename?' + p.codename + ', name:' + str(p.name)
messages.add_message(request, messages.SUCCESS, msg)
except Permission.DoesNotExist:
msg = 'PermissionNotExists'
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect(reverse('system:system_permit_list') + '?page=' + str(page))
def user_add(request):
form = UsersAddForm(request.POST)
message_error = True
msg = '??????'
if form.is_valid():
if not Users.objects.filter(users_name=form.cleaned_data['users_name']):
m2 = hashlib.md5()
m2.update(form.cleaned_data['users_password'])
f = form.save(commit=False)
f.users_password = m2.hexdigest()
f.users_create_time = datetime.now()
f.users_otp = pyotp.random_base32()
f.save()
msg = '????'
message_error = False
else:
msg = 'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors))
if message_error:
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect(reverse('users:user_add'))
else:
messages.add_message(request, messages.SUCCESS, msg)
return HttpResponseRedirect(reverse('users:user_list'))
def policy_edit(request):
if request.method == 'POST':
form = PolicyEditForm(request.POST)
message_error, msg = False, '????'
if form.is_valid():
try:
p = Policy.objects.get(policy_default__exact=1)
if form.cleaned_data["policy_default"] == 1 and p.policy_id != form.cleaned_data["policy_id"]:
message_error, msg = True, '??????????????????'
else:
f = form.save(commit=False)
f.policy_id = form.cleaned_data["policy_id"]
f.save()
except Policy.DoesNotExist:
try:
if Policy.objects.filter(policy_id=form.cleaned_data["policy_id"]):
f = form.save(commit=False)
f.policy_id = form.cleaned_data["policy_id"]
f.save()
except Policy.DoesNotExist:
message_error, msg = True, '??????????'
else:
message_error, msg = True, 'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors))
render_message(request, message_error, msg)
return HttpResponseRedirect(reverse('policy:policy_list'))
def policy_rule_add(request, rule_policy):
if request.method == 'POST':
form = PolicyRuleAddForm(request.POST)
if form.is_valid():
if not PolicyRule.objects.filter(rule_policy=rule_policy).filter(
rule_value=form.cleaned_data['rule_value']):
f = form.save(commit=False)
f.save()
messages.add_message(request, messages.SUCCESS, '??????')
return HttpResponseRedirect(reverse('policy:policy_rule_list', args=[rule_policy]))
messages.add_message(request, messages.ERROR, '???????????????')
messages.add_message(request, messages.ERROR,
'ERROR: ' + re.compile(r'<[^>]+>', re.S).sub('', str(form.errors)))
return HttpResponseRedirect(reverse('policy:policy_rule_list', args=[rule_policy]))
else:
return render_to_response('policy/rule/list.html', {'rule_policy': rule_policy},
context_instance=RequestContext(request))