def form_valid(self, form):
self.profile = form.save()
self.request.session['user_cart'] = self.request.session.session_key
user = authenticate(
email=self.profile.email,
password=self.request.POST['password1']
)
messages.add_message(
self.request, messages.SUCCESS,
'You were successfully logged in.'
)
login(self.request, user)
return super(RegistrationFormView, self).form_valid(form)
python类SUCCESS的实例源码
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 post(self, request, *args, **kwargs):
verification_key = request.POST.get("verification_key")
profile = get_object_or_404(Profile, verification_key=verification_key)
user = profile.user
# Renew user verification key
profile.verification_key = generate_user_activation_key(user.id)
profile.key_expires = set_expiration_date(settings.KEY_EXPIRES_DAY)
profile.save()
# Resend user verification email
task = ResendVerificationEmailTask()
task.delay(user.id)
messages.add_message(
request,
messages.SUCCESS,
settings.RESEND_EMAIL_VERIFICATION_MESSAGE,
)
return redirect(reverse("home"))
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,
)
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 add_view(request):
if request.POST:
Server.objects.create(
name=request.POST.get('name'),
api_username=request.POST.get('api_username'),
api_password=request.POST.get('api_password'),
api_address=request.POST.get('api_address'),
api_port=request.POST.get('api_port'),
owner=request.user,
max_member_count=32,
)
messages.add_message(
request,
messages.SUCCESS,
"Your DS has been registered. It will be manually verified and activated, so please be patient as this may take some times (from hours up to some days if we are currently too busy).",
extra_tags='success'
)
return redirect('account:home')
else:
return render(request, 'autostew_web_account/add_server.html')
def form_valid(self, form):
self.request.user.set_password(form.data.get('password_new'))
self.request.user.save()
update_session_auth_hash(self.request, self.request.user)
send_mail(
template_html_name='mail/member/reset_password.html',
template_text_name='mail/member/reset_password.text',
context={},
subject="Redéfinition de votre mot de passe",
to=self.request.user.email
)
messages.add_message(self.request, messages.SUCCESS, "Votre mot de passe a été changé avec succès.")
return redirect(reverse('homepage'))
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):
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 server_add(request):
"""
?????
:param request:
:return:
"""
msg = ''
if request.method == 'POST':
ftp_name = request.REQUEST.get('ftp_name', '') # ???ID
server_id = request.REQUEST.get('server_id', '') # Redis??
ftp_port = request.REQUEST.get('ftp_port', '') # Redis??
ftp_description = request.REQUEST.get('ftp_description', '') # redis??
ovs = OpsFtpServer(request.user)
res, msg = ovs.server_add(ftp_name, server_id, ftp_port, ftp_description)
if res:
messages.add_message(request, messages.SUCCESS, 'FTP??????????????????????')
return HttpResponseRedirect('/pureftp/s/list/')
data = Server.objects.all()
return render_to_response('pureftp/s_add.html',
{'data': data, 'msg': msg}, context_instance=RequestContext(request))
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 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 get(self, request, *args, **kwargs):
code = request.GET.get('code', '')
if not code:
raise Http404
config = SocialConfig.get_solo()
redirect_uri = self.request.build_absolute_uri(resolve_url('admin_social_networks:instagram_token'))
response = requests.post(
'https://api.instagram.com/oauth/access_token',
data={
'grant_type': 'authorization_code',
'client_id': config.instagram_client_id,
'client_secret': config.instagram_client_secret,
'redirect_uri': redirect_uri,
'code': code,
}
)
answer = response.json()
if answer and 'access_token' in answer:
SocialConfig.objects.update(instagram_access_token=answer['access_token'])
add_message(request, SUCCESS, _('Instagram access_token updated successfully!'))
return redirect('admin:social_networks_socialconfig_change')
else:
return HttpResponse(response.text)
def get(self, request, *args, **kwargs):
code = request.GET.get('code', '')
if not code:
raise Http404
config = SocialConfig.get_solo()
redirect_uri = self.request.build_absolute_uri(resolve_url('admin_social_networks:linkedin_token'))
response = requests.post(
'https://www.linkedin.com/oauth/v2/accessToken',
data={
'grant_type': 'authorization_code',
'client_id': config.linkedin_client_id,
'client_secret': config.linkedin_client_secret,
'redirect_uri': redirect_uri,
'code': code,
}
)
answer = response.json()
if answer and 'access_token' in answer:
SocialConfig.objects.update(linkedin_access_token=answer['access_token'])
add_message(request, SUCCESS, _('LinkedIn access_token updated successfully!'))
return redirect('admin:social_networks_socialconfig_change')
else:
return HttpResponse(response.text)
def form_valid(self, form):
if settings.ENABLE_USER_ACTIVATION:
user = form.save(commit=False)
user.is_active = False
user.save()
send_activation_email(self.request, user)
messages.add_message(self.request, messages.SUCCESS,
_('You are registered. To activate the account, follow the link sent to the mail.'))
else:
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(self.request, user)
messages.add_message(self.request, messages.SUCCESS, _('You are successfully registered!'))
return super(SignUpView, self).form_valid(form)
def get_redirect_url(self, *args, **kwargs):
assert 'code' in kwargs
act = get_object_or_404(Activation, code=kwargs['code'])
# Activate user's profile
user = act.user
user.is_active = True
user.save()
# Remove activation record, it is unneeded
act.delete()
messages.add_message(self.request, messages.SUCCESS, _('You have successfully activated your account!'))
login(self.request, user)
return super(ActivateView, self).get_redirect_url()
def form_valid(self, form):
user = self.request.user
email = form.cleaned_data.get('email')
email = email.lower()
if hasattr(settings, 'EMAIL_ACTIVATION_AFTER_CHANGING') and settings.EMAIL_ACTIVATION_AFTER_CHANGING:
send_activation_change_email(self.request, user, email)
messages.add_message(self.request, messages.SUCCESS,
_('To complete the change of mail, click on the link sent to it.'))
else:
user.email = email
user.save()
messages.add_message(self.request, messages.SUCCESS, _('Email successfully changed.'))
return super(ChangeEmailView, self).form_valid(form)
def form_valid(self, form):
alert = models.Alert()
alert.location = form.cleaned_data['location']
if self.request.user.is_authenticated:
#save alert
alert.user = self.request.user
alert.save()
#create a success message
messages.add_message(self.request, messages.SUCCESS, success_message)
return redirect(reverse('alert-list'))
else:
self.request.session['new-alert'] = serialize('geojson', [alert],
fields=('location',))
return redirect(reverse('create-alert-user'))
def form_valid(self, form):
#create user
UserModel = get_user_model()
user = UserModel(email=form.cleaned_data['email'])
user.set_password(form.cleaned_data['password'])
user.save()
#sign new user in
login(self.request, user)
#get the location out of the session
location = json.loads(self.request.session['new-alert'])
#save alert
alert = models.Alert()
alert.location = json.dumps(location['features'][0]['geometry'])
alert.user = user
alert.save()
#create a success message
messages.add_message(self.request, messages.SUCCESS, success_message)
return redirect(reverse('alert-list'))
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 custom_mail_confirm(self, request):
if request.method == "POST":
form_id = request.session["mailform_id"]
advisor = request.session["mailform_advisor_" + form_id]
email_addresses = request.session[
"mailform_addresses_" + form_id]
body = request.session["mailform_body_" + form_id]
subject = request.session["mailform_subject_" + form_id]
sent_amount = mails.send_custom(
advisor, email_addresses, subject, body)
messages.add_message(
request,
messages.SUCCESS,
"%s mails were sent successfully" % sent_amount)
referer = request.session["mailform_referer_" + form_id]
return HttpResponseRedirect(referer)
else:
return HttpResponseRedirect(reverse('admin:index'))
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 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_add(request):
"""
????
:param request:
:return:
"""
if request.method == 'POST':
p = Permission()
p.name = request.POST['name']
p.codename = request.POST['codename']
p.content_type_id = request.POST['content_type_id']
p.save()
res, msg = True, '???????name: ' + request.POST['name'] + ' ,codename' + request.POST['codename']
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(reverse('system:system_permit_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))