我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.messages.success()。
def create(request): error = None group_name = '' if request.method == 'POST': group_name = request.POST.get('group_name', '') try: create_usergroup(request.user, group_name) msg = _('Group "{0}" was created.').format(group_name) messages.success(request, msg) return redirect('groups_show', group_name) except GroupError as e: error = e.message return TemplateResponse(request, 'groups/create.html', { 'error': error, 'group_name': group_name, })
def event_signin(request, *args, **kwargs): if not request.user.is_anonymous(): logout(request) event = Event.objects.get(pk=kwargs.get('pk', None)) if request.method == "GET": return render(request, 'signin_sheets/participant_signin.html', {'form': ParticipantSigninForm, 'event': event}) elif request.method == "POST": form = ParticipantSigninForm(request.POST) if form.is_valid(): user = form.save() user.event = Event.objects.get(pk=kwargs.get('pk')) user.save() messages.success(request, "Your information has been saved.<br>Thanks for signing in!") return redirect(reverse('event-signin', kwargs={'pk': kwargs.get('pk')})) return redirect(reverse('event-list'))
def invite(request, group_name): group = get_object_or_404(Group, name=group_name) if not group.properties.admins.filter(pk=request.user.pk): raise PermissionDenied() if request.method == 'POST': form = InvitationForm(request.POST, group=group, user=request.user) if form.is_valid(): subject = u'Neue Gruppeneinladung / new group invitation' invitations = form.get_invitations() for invitation in invitations: invitation.save() _send_invitation_mail(request, invitation, subject, 'new_invitation') messages.success(request, _('Invitation was sent.')) return redirect('groups_show', group_name) else: form = InvitationForm(group=group, user=request.user) return TemplateResponse(request, 'groups/invite.html', { 'group': group, 'form': form })
def get(self, request, *args, **kwargs): """Process checkout when view triggered by GET request.""" logger = logging.getLogger('django') try: self.item = Lendable(type=self.kwargs.get('item_subtype', None), user=self.request.user) self.item.checkout() self.item.save() except Exception as e: messages.error(request, e) logger.exception('%s: %s' % (type(e).__name__, e)) return redirect(reverse('library:index')) else: messages.success( request, "'%s' is checked out to you until %s." % (self.item.name, formatting_filters.format_date(self.item.due_on)) ) return super(CheckoutView, self).get(request, *args, **kwargs)
def checkin(request, primary_key): """Checkin the :model:`library.Lendable`. Cleanup and delete Lendable. Redirect: :view:`library.index` """ item = get_object_or_404(Lendable.all_types, pk=primary_key, user=request.user) try: item.checkin() except Exception as e: messages.error(request, e) else: messages.success(request, "'%s' returned." % (item.name)) return redirect(reverse('library:index'))
def choose_name(request): username = request.POST['username'] try: user = User.objects.create(username=username) if request.user.is_authenticated(): old_user = request.user django_logout(request) old_user.delete() _login_user(request, user) messages.success(request, 'You have chosen "{}"!'.format(username)) except IntegrityError: messages.error(request, 'Sorry, "{}" is already taken :('.format(username)) return redirect(request.GET.get('next', '/')) # Gets context of previous and current player actions for Hotseat Gameplay
def update(request, site_id=None): site_settings = get_object_or_404(SiteSettings, pk=site_id) site = site_settings.site site_settings_form = SiteSettingForm( request.POST or None, instance=site_settings) site_form = SiteForm(request.POST or None, instance=site) authorization_qs = AuthorizationKey.objects.filter( site_settings=site_settings) formset = AuthorizationKeyFormSet( request.POST or None, queryset=authorization_qs, initial=[{'site_settings': site_settings}]) if all([site_settings_form.is_valid(), site_form.is_valid(), formset.is_valid()]): site = site_form.save() site_settings_form.instance.site = site site_settings = site_settings_form.save() formset.save() messages.success(request, _('Updated site %s') % site_settings) return redirect('dashboard:site-update', site_id=site_settings.id) ctx = {'site': site_settings, 'site_settings_form': site_settings_form, 'site_form': site_form, 'formset': formset} return TemplateResponse(request, 'dashboard/sites/detail.html', ctx)
def product_class_delete(request, pk): product_class = get_object_or_404(ProductClass, pk=pk) if request.method == 'POST': product_class.delete() messages.success( request, pgettext_lazy( 'Dashboard message', 'Deleted product type %s') % product_class) return redirect('dashboard:product-class-list') ctx = {'product_class': product_class, 'products': product_class.products.all()} return TemplateResponse( request, 'dashboard/product/product_class/modal/confirm_delete.html', ctx)
def stock_delete(request, product_pk, variant_pk, stock_pk): product = get_object_or_404(Product, pk=product_pk) variant = get_object_or_404(product.variants, pk=variant_pk) stock = get_object_or_404(Stock, pk=stock_pk) if request.method == 'POST': stock.delete() messages.success( request, pgettext_lazy('Dashboard message', 'Deleted stock')) return redirect( 'dashboard:variant-details', product_pk=product.pk, variant_pk=variant.pk) ctx = {'product': product, 'stock': stock, 'variant': variant} return TemplateResponse( request, 'dashboard/product/stock/modal/confirm_delete.html', ctx)
def product_image_edit(request, product_pk, img_pk=None): product = get_object_or_404(Product, pk=product_pk) if img_pk: product_image = get_object_or_404(product.images, pk=img_pk) else: product_image = ProductImage(product=product) form = forms.ProductImageForm( request.POST or None, request.FILES or None, instance=product_image) if form.is_valid(): product_image = form.save() if img_pk: msg = pgettext_lazy( 'Dashboard message', 'Updated image %s') % product_image.image.name else: msg = pgettext_lazy( 'Dashboard message', 'Added image %s') % product_image.image.name messages.success(request, msg) return redirect('dashboard:product-image-list', product_pk=product.pk) ctx = {'form': form, 'product': product, 'product_image': product_image} return TemplateResponse( request, 'dashboard/product/product_image/form.html', ctx)
def variant_edit(request, product_pk, variant_pk=None): product = get_object_or_404( Product.objects.all(), pk=product_pk) if variant_pk: variant = get_object_or_404(product.variants.all(), pk=variant_pk) else: variant = ProductVariant(product=product) form = forms.ProductVariantForm(request.POST or None, instance=variant) attribute_form = forms.VariantAttributeForm( request.POST or None, instance=variant) if all([form.is_valid(), attribute_form.is_valid()]): form.save() attribute_form.save() msg = pgettext_lazy( 'Dashboard message', 'Saved variant %s') % variant.name messages.success(request, msg) return redirect( 'dashboard:variant-details', product_pk=product.pk, variant_pk=variant.pk) ctx = {'attribute_form': attribute_form, 'form': form, 'product': product, 'variant': variant} return TemplateResponse( request, 'dashboard/product/product_variant/form.html', ctx)
def variant_delete(request, product_pk, variant_pk): product = get_object_or_404(Product, pk=product_pk) variant = get_object_or_404(product.variants, pk=variant_pk) if request.method == 'POST': variant.delete() messages.success( request, pgettext_lazy( 'Dashboard message', 'Deleted variant %s') % variant.name) return redirect('dashboard:product-detail', pk=product.pk) ctx = {'is_only_variant': product.variants.count() == 1, 'product': product, 'variant': variant} return TemplateResponse( request, 'dashboard/product/product_variant/modal/confirm_delete.html', ctx)
def stock_location_edit(request, location_pk=None): if location_pk: location = get_object_or_404(StockLocation, pk=location_pk) else: location = StockLocation() form = forms.StockLocationForm(request.POST or None, instance=location) if form.is_valid(): form.save() msg = pgettext_lazy( 'Dashboard message for stock location', 'Updated location') if location_pk else pgettext_lazy( 'Dashboard message for stock location', 'Added location') messages.success(request, msg) return redirect('dashboard:product-stock-location-list') return TemplateResponse( request, 'dashboard/product/stock_location/form.html', {'form': form, 'location': location})
def category_edit(request, root_pk=None): category = get_object_or_404(Category, pk=root_pk) form = CategoryForm(request.POST or None, instance=category, parent_pk=category.parent_id) status = 200 if form.is_valid(): category = form.save() messages.success( request, pgettext_lazy( 'Dashboard message', 'Updated category %s') % category) if root_pk: return redirect('dashboard:category-list', root_pk=root_pk) else: return redirect('dashboard:category-list') elif form.errors: status = 400 ctx = {'category': category, 'form': form, 'status': status} template = 'dashboard/category/modal/edit.html' return TemplateResponse(request, template, ctx, status=status)
def order_add_note(request, order_pk): order = get_object_or_404(Order, pk=order_pk) note = OrderNote(order=order, user=request.user) form = OrderNoteForm(request.POST or None, instance=note) status = 200 if form.is_valid(): form.save() msg = pgettext_lazy( 'Dashboard message related to an order', 'Added note') order.create_history_entry(comment=msg, user=request.user) messages.success(request, msg) elif form.errors: status = 400 ctx = {'order': order, 'form': form} ctx.update(csrf(request)) template = 'dashboard/order/modal/add_note.html' return TemplateResponse(request, template, ctx, status=status)
def capture_payment(request, order_pk, payment_pk): order = get_object_or_404(Order, pk=order_pk) payment = get_object_or_404(order.payments, pk=payment_pk) amount = order.get_total().quantize('0.01').gross form = CapturePaymentForm(request.POST or None, payment=payment, initial={'amount': amount}) if form.is_valid() and form.capture(): amount = form.cleaned_data['amount'] msg = pgettext_lazy( 'Dashboard message related to a payment', 'Captured %(amount)s') % {'amount': gross(amount)} payment.order.create_history_entry(comment=msg, user=request.user) messages.success(request, msg) return redirect('dashboard:order-details', order_pk=order.pk) status = 400 if form.errors else 200 ctx = {'captured': payment.captured_amount, 'currency': payment.currency, 'form': form, 'order': order, 'payment': payment} return TemplateResponse(request, 'dashboard/order/modal/capture.html', ctx, status=status)
def refund_payment(request, order_pk, payment_pk): order = get_object_or_404(Order, pk=order_pk) payment = get_object_or_404(order.payments, pk=payment_pk) amount = payment.captured_amount form = RefundPaymentForm(request.POST or None, payment=payment, initial={'amount': amount}) if form.is_valid() and form.refund(): amount = form.cleaned_data['amount'] msg = pgettext_lazy( 'Dashboard message related to a payment', 'Refunded %(amount)s') % {'amount': gross(amount)} payment.order.create_history_entry(comment=msg, user=request.user) messages.success(request, msg) return redirect('dashboard:order-details', order_pk=order.pk) status = 400 if form.errors else 200 ctx = {'captured': payment.captured_amount, 'currency': payment.currency, 'form': form, 'order': order, 'payment': payment} return TemplateResponse(request, 'dashboard/order/modal/refund.html', ctx, status=status)
def orderline_cancel(request, order_pk, line_pk): order = get_object_or_404(Order, pk=order_pk) item = get_object_or_404(OrderedItem.objects.filter( delivery_group__order=order), pk=line_pk) form = CancelItemsForm(data=request.POST or None, item=item) status = 200 if form.is_valid(): msg = pgettext_lazy( 'Dashboard message related to an order line', 'Cancelled item %s') % item with transaction.atomic(): form.cancel_item() order.create_history_entry(comment=msg, user=request.user) messages.success(request, msg) return redirect('dashboard:order-details', order_pk=order.pk) elif form.errors: status = 400 ctx = {'order': order, 'item': item, 'form': form} return TemplateResponse( request, 'dashboard/order/modal/cancel_line.html', ctx, status=status)
def ship_delivery_group(request, order_pk, group_pk): order = get_object_or_404(Order, pk=order_pk) group = get_object_or_404(order.groups.all(), pk=group_pk) form = ShipGroupForm(request.POST or None, instance=group) status = 200 if form.is_valid(): with transaction.atomic(): form.save() msg = pgettext_lazy( 'Dashboard message related to a delivery group', 'Shipped %s') % group messages.success(request, msg) group.order.create_history_entry(comment=msg, user=request.user) return redirect('dashboard:order-details', order_pk=order_pk) elif form.errors: status = 400 ctx = {'order': order, 'group': group, 'form': form} template = 'dashboard/order/modal/ship_delivery_group.html' return TemplateResponse(request, template, ctx, status=status)
def cancel_delivery_group(request, order_pk, group_pk): order = get_object_or_404(Order, pk=order_pk) group = get_object_or_404(order.groups.all(), pk=group_pk) form = CancelGroupForm(request.POST or None, delivery_group=group) status = 200 if form.is_valid(): with transaction.atomic(): form.cancel_group() msg = pgettext_lazy( 'Dashboard message related to a delivery group', 'Cancelled %s') % group messages.success(request, msg) group.order.create_history_entry(comment=msg, user=request.user) return redirect('dashboard:order-details', order_pk=order_pk) elif form.errors: status = 400 ctx = {'order': order, 'group': group} template = 'dashboard/order/modal/cancel_delivery_group.html' return TemplateResponse(request, template, ctx, status=status)
def address_view(request, order_pk, address_type): order = Order.objects.get(pk=order_pk) if address_type == 'shipping': address = order.shipping_address success_msg = pgettext_lazy( 'Dashboard message', 'Updated shipping address') else: address = order.billing_address success_msg = pgettext_lazy( 'Dashboard message', 'Updated billing address') form = AddressForm(request.POST or None, instance=address) if form.is_valid(): form.save() order.create_history_entry(comment=success_msg, user=request.user) messages.success(request, success_msg) return redirect('dashboard:order-details', order_pk=order_pk) ctx = {'order': order, 'address_type': address_type, 'form': form} return TemplateResponse(request, 'dashboard/order/address_form.html', ctx)
def cancel_order(request, order_pk): status = 200 order = get_object_or_404(Order, pk=order_pk) form = CancelOrderForm(request.POST or None, order=order) if form.is_valid(): msg = pgettext_lazy('Dashboard message', 'Cancelled order') with transaction.atomic(): form.cancel_order() order.create_history_entry(comment=msg, user=request.user) messages.success(request, 'Order cancelled') return redirect('dashboard:order-details', order_pk=order.pk) # TODO: send status confirmation email elif form.errors: status = 400 ctx = {'order': order} return TemplateResponse(request, 'dashboard/order/modal/cancel_order.html', ctx, status=status)
def sale_edit(request, pk=None): if pk: instance = get_object_or_404(Sale, pk=pk) else: instance = Sale() form = forms.SaleForm( request.POST or None, instance=instance) if form.is_valid(): instance = form.save() msg = pgettext_lazy( 'Sale (discount) message', 'Updated sale') if pk else pgettext_lazy( 'Sale (discount) message', 'Added sale') messages.success(request, msg) return redirect('dashboard:sale-update', pk=instance.pk) ctx = {'sale': instance, 'form': form} return TemplateResponse(request, 'dashboard/discount/sale/form.html', ctx)
def company_create(request): form = CompanyForm(request.POST or None, request.FILES or None) if form.is_valid(): Company.objects.create( name=form.cleaned_data.get("name"), abn=form.cleaned_data.get("abn"), description=form.cleaned_data.get("description"), logo=request.FILES['logo'] ) messages.success(request, 'Record successfully created') return redirect(company_list) context = { "title": "Create a new Company", "form": form, } return render(request, "companies-create.html", context)
def team_apply(request, slug): team = get_object_or_404(Team, slug=slug) state = team.get_state_for_user(request.user) if team.access == "invitation" and state is None and not request.user.is_staff: raise Http404() if can_apply(team, request.user) and request.method == "POST": membership, created = Membership.objects.get_or_create(team=team, user=request.user) membership.state = "applied" membership.save() managers = [m.user.email for m in team.managers()] send_email(managers, "teams_user_applied", context={ "team": team, "user": request.user }) messages.success(request, "Applied to join team.") return redirect("team_detail", slug=slug) else: return redirect("team_detail", slug=slug)
def speaker_create_staff(request, pk): user = get_object_or_404(User, pk=pk) if not request.user.is_staff: raise Http404 try: return redirect(user.speaker_profile) except ObjectDoesNotExist: pass if request.method == "POST": form = SpeakerForm(request.POST, request.FILES) if form.is_valid(): speaker = form.save(commit=False) speaker.user = user speaker.save() messages.success(request, "Speaker profile created.") return redirect("user_list") else: form = SpeakerForm(initial={"name": user.get_full_name()}) return render(request, "speakers/speaker_create.html", { "form": form, })
def speaker_edit(request, pk=None): if pk is None: try: speaker = request.user.speaker_profile except Speaker.DoesNotExist: return redirect("speaker_create") else: if request.user.is_staff: speaker = get_object_or_404(Speaker, pk=pk) else: raise Http404() if request.method == "POST": form = SpeakerForm(request.POST, request.FILES, instance=speaker) if form.is_valid(): form.save() messages.success(request, "Speaker profile updated.") return redirect("dashboard") else: form = SpeakerForm(instance=speaker) return render(request, "speakers/speaker_edit.html", { "form": form, })
def proposal_cancel(request, pk): queryset = ProposalBase.objects.select_related("speaker") proposal = get_object_or_404(queryset, pk=pk) proposal = ProposalBase.objects.get_subclass(pk=proposal.pk) if proposal.speaker.user != request.user: return HttpResponseForbidden() if request.method == "POST": proposal.cancelled = True proposal.save() # @@@ fire off email to submitter and other speakers messages.success(request, "%s has been cancelled" % proposal.title) return redirect("dashboard") return render(request, "proposals/proposal_cancel.html", { "proposal": proposal, })
def proposal_leave(request, pk): queryset = ProposalBase.objects.select_related("speaker") proposal = get_object_or_404(queryset, pk=pk) proposal = ProposalBase.objects.get_subclass(pk=proposal.pk) try: speaker = proposal.additional_speakers.get(user=request.user) except ObjectDoesNotExist: return HttpResponseForbidden() if request.method == "POST": proposal.additional_speakers.remove(speaker) # @@@ fire off email to submitter and other speakers messages.success(request, "You are no longer speaking on %s" % proposal.title) return redirect("dashboard") ctx = { "proposal": proposal, } return render(request, "proposals/proposal_leave.html", ctx)
def post_model_create_view(request): form = PostModelForm(request.POST or None) context = { "form": form } if form.is_valid(): obj = form.save(commit=False) #print(obj.title) obj.save() messages.success(request, "Created a new blog post!") context = { "form": PostModelForm() } #return HttpResponseRedirect("/blog/{num}".format(num=obj.id)) template = "blog/create-view.html" return render(request, template, context) #@login_required
def scan_scan_list(request: HttpRequest, scan_list_id: int) -> HttpResponse: """Schedule the scan of a scan list.""" scan_list = get_object_or_404( ScanList.objects.prefetch_related(Prefetch( 'sites', queryset=Site.objects.select_related('last_scan') \ .annotate_most_recent_scan_start() \ .annotate_most_recent_scan_end_or_null()) ), pk=scan_list_id) was_any_site_scannable = scan_list.scan() if was_any_site_scannable: num_scanning_sites = Scan.objects.filter(end__isnull=True).count() messages.success(request, _("Scans for this list have been scheduled. "+ \ "The total number of sites in the scanning queue "+ \ "is %i (including yours)." % num_scanning_sites)) else: messages.warning(request, _('All sites have been scanned recently. Please wait 30 minutes and try again.')) return redirect(reverse('frontend:view_scan_list', args=(scan_list_id,)))
def remove(request, device_id): device_qs = ( twofa.models.Device.objects .active_for_user(request.user).select_subclasses()) device = get_object_or_404(device_qs, pk=device_id) if not device.can_delete(): messages.error( request, _('The "%(auth_name)s" authenticator cannot be removed.') % {'auth_name': device.name()}) return redirect('twofa:list') device.deleted_at = timezone.now() device.save() messages.success( request, _('The "%(auth_name)s" authenticator has been removed from your account.') % { 'auth_name': device.name()}) if not twofa.models.Device.objects.active_for_user(request.user).exclude_backup().exists(): request.user.twofa_enabled = False request.user.save() messages.info( request, _('Since you removed the last authenticator from your account, ' 'two-factor authentication has now been disabled.')) return redirect('twofa:list')
def verify_step2(request, uidb64, token): bytes_uid = urlsafe_base64_decode(uidb64) try: uid = int(bytes_uid) except ValueError: raise SuspiciousOperation('verify_step2 received invalid base64 user ID: {}'.format( bytes_uid)) if uid != request.user.id: raise PermissionDenied('UID mismatch - user is {}, request was for {}'.format( request.user.id, uid)) user = get_object_or_404(models.User, pk=uid) if not verify_token_generator.check_token(user, token): raise Http404('token invalid') if not user.email_verified: user.email_verified = True user.save() messages.success(request, _('Your email has been verified successfully. Thanks!')) else: messages.info(request, _('Your email address has already been verified.')) return redirect('index')
def post(self, request): target = request.POST.get('target') pk = request.POST.get('user') user = User.objects.get(pk=pk) if 'troubleshooter' in target: user.is_troubleshooter = target[-1] == 'y' elif 'backoffice' in target: user.is_backoffice_user = target[-1] == 'y' elif 'superuser' in target: user.is_superuser = target[-1] == 'y' user.save() if target[-1] == 'y': messages.success(request, _('User rights have been expanded')) else: messages.success(request, _('User rights have been curtailed.')) return redirect('backoffice:wizard-users')
def reverse_session_view(request: HttpRequest, pk: int) -> Union[HttpRequest, HttpResponseRedirect]: session = get_object_or_404(CashdeskSession, pk=pk) if request.method == 'POST': try: reverse_session(session) except FlowError as e: messages.error(request, str(e)) else: messages.success(request, _('All transactions in the session have been cancelled.')) return redirect('backoffice:session-detail', pk=pk) elif request.method == 'GET': return render(request, 'backoffice/reverse_session.html', { 'session': session, })
def add_slack_btn(request): code = request.GET.get("code", "") if len(code) < 8: return HttpResponseBadRequest() result = requests.post("https://slack.com/api/oauth.access", { "client_id": settings.SLACK_CLIENT_ID, "client_secret": settings.SLACK_CLIENT_SECRET, "code": code }) doc = result.json() if doc.get("ok"): channel = Channel() channel.user = request.team.user channel.kind = "slack" channel.value = result.text channel.save() channel.assign_all_checks() messages.success(request, "The Slack integration has been added!") else: s = doc.get("error") messages.warning(request, "Error message from slack: %s" % s) return redirect("hc-channels")
def set_password(request, token): profile = request.user.profile if not check_password(token, profile.token): return HttpResponseBadRequest() if request.method == "POST": form = SetPasswordForm(request.POST) if form.is_valid(): password = form.cleaned_data["password"] request.user.set_password(password) request.user.save() profile.token = "" profile.save() # Setting a password logs the user out, so here we # log them back in. u = authenticate(username=request.user.email, password=password) auth_login(request, u) messages.success(request, "Your password has been set!") return redirect("hc-profile") return render(request, "accounts/set_password.html", {})
def change_password(request): if request.method == 'POST': user = request.user old_password = request.POST.get('old_password') new_password = request.POST.get('new_password') confirm_password = request.POST.get('confirm_password') if authenticate(username=user.username, password=old_password): if new_password == confirm_password: user.set_password(new_password) user.save() messages.success(request, 'Password Updated') else: messages.warning(request, 'Passwords do not match') else: messages.warning(request, 'Invalid Password') return render(request, 'taskManager/change_password.html', {'user': request.user})
def post(self, request, *args, **kwargs): ids = request.POST.getlist('selected') apps = models.Application.objects.filter(pk__in=ids).all() mails = [] errors = 0 for app in apps: try: app.invite(request.user) m = emails.create_invite_email(app, request) mails.append(m) except ValidationError: errors += 1 if mails: send_batch_emails(mails) messages.success(request, "%s applications invited" % len(mails)) else: messages.error(request, "%s applications not invited" % errors) return HttpResponseRedirect(reverse('invite_list'))
def post(self, request, *args, **kwargs): try: form = forms.ReceiptSubmissionReceipt(request.POST, request.FILES, instance=request.user.reimbursement) except: form = forms.ReceiptSubmissionReceipt(request.POST, request.FILES) if form.is_valid(): reimb = form.save(commit=False) reimb.hacker = request.user reimb.save() messages.success(request, 'We have now received your reimbursement. ' 'Processing will take some time, so please be patient.') return HttpResponseRedirect(reverse('reimbursement_dashboard')) else: c = self.get_context_data() c.update({'form': form}) return render(request, self.template_name, c)
def post(self, request, *args, **kwargs): ids = request.POST.getlist('selected') reimbs = models.Reimbursement.objects.filter(pk__in=ids).all() mails = [] errors = 0 for reimb in reimbs: try: assigned_money = request.POST.get('am_' + str(reimb.pk)) reimb.assigned_money = assigned_money reimb.send(request.user) m = emails.create_reimbursement_email(reimb, request) mails.append(m) except ValidationError: errors += 1 if mails: send_batch_emails(mails) messages.success(request, "%s reimbursements sent" % len(mails)) else: messages.error(request, "%s reimbursements not sent" % errors) return HttpResponseRedirect(reverse('send_reimbursement'))
def activate(request, uid, token): try: uid = force_text(urlsafe_base64_decode(uid)) user = User.objects.get(pk=uid) if request.user != user: messages.warning(request, "User email can be verified") return redirect('root') except (TypeError, ValueError, OverflowError, User.DoesNotExist): messages.warning(request, "User email can be verified") return redirect('root') if account_activation_token.check_token(user, token): messages.success(request, "Email verified!") user.email_verified = True user.save() auth.login(request, user) else: messages.error(request, "This email verification url has expired") return redirect('root')
def post(self, request, *args, **kwargs): new_application = True try: form = forms.ApplicationForm(request.POST, request.FILES, instance=request.user.application) new_application = False except: form = forms.ApplicationForm(request.POST, request.FILES) if form.is_valid(): application = form.save(commit=False) application.user = request.user application.save() if new_application: messages.success(request, 'We have now received your application. ' 'Processing your application will take some time, so please be patient.') else: messages.success(request, 'Application changes saved successfully!') return HttpResponseRedirect(reverse('root')) else: c = self.get_context_data() c.update({'form': form}) return render(request, self.template_name, c)
def ArticleEdit(request): if request.method == "POST": ueditorform = UEditorForm(request.POST) user = request.user if ueditorform.is_valid(): article = Article.objects.create(author_id=user.pk, category_id=ueditorform.clean()['category'], title=ueditorform.clean()['title'], article_from=ueditorform.clean()['article_from'], summary=ueditorform.clean()['summary'], tags=ueditorform.clean()['tags'], content=ueditorform.clean()['content'], ) if article is not None: user.topic_num += 1 user.save() messages.success(request, '?????????????') return HttpResponseRedirect(reverse('index-view')) else: ueditorform = UEditorForm() return render(request,'blog/article_edit.html',{'form': ueditorform})
def password(request): user = request.user if request.method == "POST": form = PasswordChangeForm(request.POST) if form.is_valid(): data = form.clean() if user.check_password(data["old_password"]): user.set_password(data["password"]) user.save() messages.success(request, "?????????????") auth_logout(request) return HttpResponseRedirect(reverse("login")) else: messages.error(request,'????????') return render(request, "users/password.html", {'errors': form.errors}) else: form = PasswordChangeForm() return render(request, "users/password.html")
def form_valid(self, form): form.instance.remote_address = self.request.META.get( 'HTTP_X_REAL_IP', '0.0.0.0' ) try: self.object = form.save() form.send_email(request=self.request) except: # pragma: no cover messages.error(self.request, 'An internal server error occured.', extra_tags='form_invalid', ) else: messages.success(self.request, 'Thanks! Someone will contact you soon.', extra_tags='form_valid', ) return super(ContactView, self).form_valid(form)
def create_person_patch(request, jur_id): if request.method == 'POST': p = Person.objects.get(id=request.POST['person']) # if any error occur then `create` will throw error. IssueResolverPatch.objects.create( content_object=p, jurisdiction_id=jur_id, status='unreviewed', old_value=request.POST['old_value'], new_value=request.POST['new_value'], source=request.POST.get('source'), category=request.POST['category'], alert='error', note=request.POST.get('note'), applied_by='admin', ) messages.success(request, "Successfully created Patch") people = Person.objects.filter( memberships__organization__jurisdiction_id=jur_id).distinct() context = {'jur_id': jur_id, 'people': people} return render(request, 'admintools/create_person_patch.html', context) # Data Quality Exceptions
def form_valid(self, form): """Posts entitlement data to API""" try: data = form.cleaned_data urlpath = '/users/{}/entitlements'.format(data['user_id']) payload = { 'bank_id': data['bank_id'], 'role_name': data['role_name'], } entitlement = self.api.post(urlpath, payload=payload) except APIError as err: messages.error(self.request, err) return super(DetailView, self).form_invalid(form) msg = 'Entitlement with role {} has been added.'.format( entitlement['role_name']) messages.success(self.request, msg) self.success_url = self.request.path return super(DetailView, self).form_valid(form)