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类add_message()的实例源码
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 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 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 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 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 is_open(self):
code = self.request.REQUEST.get("code")
if code:
try:
self.signup_code = SignupCode.check_in_signupcode(code)
except SignupCode.InvalidCode:
if not settings.ACCOUNT_OPEN_SIGNUP:
return False
else:
if self.messages.get("invalid_signup_code"):
messages.add_message(
self.request,
self.messages["invalid_signup_code"]["level"],
self.messages["invalid_signup_code"]["text"] % {
"code": code
}
)
return True
else:
return True
else:
return settings.ACCOUNT_OPEN_SIGNUP
def post(self, *args, **kwargs):
self.object = confirmation = self.get_object()
confirmation.confirm()
user = confirmation.email_address.user
user.is_active = True
user.save()
redirect_url = self.get_redirect_url()
if not redirect_url:
ctx = self.get_context_data()
return self.render_to_response(ctx)
if self.messages.get("email_confirmed"):
messages.add_message(
self.request,
self.messages["email_confirmed"]["level"],
self.messages["email_confirmed"]["text"] % {
"email": confirmation.email_address.email
}
)
return redirect(redirect_url)
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 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, *args, **kwargs):
self.object = confirmation = self.get_object()
confirmation.confirm()
self.after_confirmation(confirmation)
redirect_url = self.get_redirect_url()
if not redirect_url:
ctx = self.get_context_data()
return self.render_to_response(ctx)
if self.messages.get("email_confirmed"):
messages.add_message(
self.request,
self.messages["email_confirmed"]["level"],
self.messages["email_confirmed"]["text"].format(**{
"email": confirmation.email_address.email
})
)
return redirect(redirect_url)
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, *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 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 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 user_edit(request):
uid = request.REQUEST.get('uid', '')
if request.method == 'POST':
ops_server = OpsUser(request.user)
res, msg = ops_server.user_edit(request.POST)
# ????
messages.add_message(request, messages.SUCCESS, msg)
return HttpResponseRedirect('/system/u/list/')
else:
data = User.objects.get(pk=uid)
# group
groups = Group.objects.all()
group = data.groups.all()
# permission
permissions = Permission.objects.all()
permission = data.user_permissions.all()
return render_to_response('system/edit.html',
{'data': data, 'permission': permission,'permissions': permissions,'groups': groups,
'group': group})
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})