我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.template.response.TemplateResponse()。
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 password_reset_complete(request, template_name='registration/password_reset_complete.html', extra_context=None): warnings.warn("The password_reset_complete() view is superseded by the " "class-based PasswordResetCompleteView().", RemovedInDjango21Warning, stacklevel=2) context = { 'login_url': resolve_url(settings.LOGIN_URL), 'title': _('Password reset complete'), } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context) # Class-based password reset views # - PasswordResetView sends the mail # - PasswordResetDoneView shows a success message for the above # - PasswordResetConfirmView checks the link the user clicked and # prompts for a new password # - PasswordResetCompleteView shows a success message for the above
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 change_email(request, token): try: data = signing.loads(token, max_age=TOKEN_MAX_AGE) except signing.SignatureExpired: return TemplateResponse(request, 'registration/token_expired.html') except signing.BadSignature: return TemplateResponse(request, 'registration/token_invalid.html') if request.user.username != data.get('username'): return TemplateResponse(request, 'registration/token_invalid.html') email = data.get('email') try: validate_email(email) except ValidationError: return TemplateResponse(request, 'registration/token_invalid.html') request.user.email = email request.user.save() messages.success(request, _('Your email address has been changed.')) return redirect('registration_account')
def _send_mail_or_error_page(subject, content, address, request): try: send_mail(subject, content, None, [address]) if settings.DEBUG: print(u"VALIDATION MAIL to {0}\nSubject: {1}\n{2}".format( address, subject, content)) except SMTPRecipientsRefused as e: wrong_email, (error_code, error_msg) = e.recipients.items()[0] unknown = 'User unknown' in error_msg if not unknown: error_email_content = u'{0}: {1}'.format(e.__class__.__name__, repr(e.recipients)) send_mail( _('Registration: Sending mail failed: {}'.format(address)), error_email_content, None, [settings.TEAM_EMAIL]) return TemplateResponse(request, 'registration/email_error.html', { 'unknown': unknown, 'error_code': error_code, 'error_msg': error_msg, 'recipient': wrong_email }) return redirect('registration_request_successful', address)
def index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap'): req_protocol = request.scheme req_site = get_current_site(request) sites = [] for section, site in sitemaps.items(): if callable(site): site = site() protocol = req_protocol if site.protocol is None else site.protocol sitemap_url = urlresolvers.reverse( sitemap_url_name, kwargs={'section': section}) absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url) sites.append(absolute_url) for page in range(2, site.paginator.num_pages + 1): sites.append('%s?p=%s' % (absolute_url, page)) return TemplateResponse(request, template_name, {'sitemaps': sites}, content_type=content_type)
def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) app_name = apps.get_app_config(app_label).verbose_name context = dict(self.each_context(request), title=_('%(app)s administration') % {'app': app_name}, app_list=[app_dict], app_label=app_label, ) context.update(extra_context or {}) request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site.
def render_delete_form(self, request, context): opts = self.model._meta app_label = opts.app_label request.current_app = self.admin_site.name context.update( to_field_var=TO_FIELD_VAR, is_popup_var=IS_POPUP_VAR, ) return TemplateResponse(request, self.delete_confirmation_template or [ "admin/{}/{}/delete_confirmation.html".format(app_label, opts.model_name), "admin/{}/delete_confirmation.html".format(app_label), "admin/delete_confirmation.html" ], context)
def index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap'): req_protocol = request.scheme req_site = get_current_site(request) sites = [] for section, site in sitemaps.items(): if callable(site): site = site() protocol = req_protocol if site.protocol is None else site.protocol sitemap_url = reverse(sitemap_url_name, kwargs={'section': section}) absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url) sites.append(absolute_url) for page in range(2, site.paginator.num_pages + 1): sites.append('%s?p=%s' % (absolute_url, page)) return TemplateResponse(request, template_name, {'sitemaps': sites}, content_type=content_type)
def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) app_name = apps.get_app_config(app_label).verbose_name context = dict( self.each_context(request), title=_('%(app)s administration') % {'app': app_name}, app_list=[app_dict], app_label=app_label, ) context.update(extra_context or {}) request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site.
def render_delete_form(self, request, context): opts = self.model._meta app_label = opts.app_label request.current_app = self.admin_site.name context.update( to_field_var=TO_FIELD_VAR, is_popup_var=IS_POPUP_VAR, media=self.media, ) return TemplateResponse( request, self.delete_confirmation_template or [ "admin/{}/{}/delete_confirmation.html".format(app_label, opts.model_name), "admin/{}/delete_confirmation.html".format(app_label), "admin/delete_confirmation.html", ], context, )
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_list(request): classes = ProductClass.objects.all().prefetch_related( 'product_attributes', 'variant_attributes').order_by('name') form = forms.ProductClassForm(request.POST or None) if form.is_valid(): return redirect('dashboard:product-class-add') classes = get_paginator_items( classes, DASHBOARD_PAGINATE_BY, request.GET.get('page')) classes.object_list = [ (pc.pk, pc.name, pc.has_variants, pc.product_attributes.all(), pc.variant_attributes.all()) for pc in classes.object_list] ctx = {'form': form, 'product_classes': classes} return TemplateResponse( request, 'dashboard/product/product_class/list.html', ctx)
def product_class_edit(request, pk): product_class = get_object_or_404( ProductClass, pk=pk) form = forms.ProductClassForm(request.POST or None, instance=product_class) if form.is_valid(): product_class = form.save() msg = pgettext_lazy( 'Dashboard message', 'Updated product type %s') % product_class messages.success(request, msg) return redirect('dashboard:product-class-update', pk=pk) ctx = {'form': form, 'product_class': product_class} return TemplateResponse( request, 'dashboard/product/product_class/form.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_edit(request, product_pk, variant_pk, stock_pk=None): product = get_object_or_404(Product, pk=product_pk) variant = get_object_or_404(product.variants, pk=variant_pk) if stock_pk: stock = get_object_or_404(variant.stock, pk=stock_pk) else: stock = Stock() form = forms.StockForm( request.POST or None, instance=stock, variant=variant) if form.is_valid(): form.save() messages.success( request, pgettext_lazy('Dashboard message', 'Saved stock')) return redirect( 'dashboard:variant-details', product_pk=product.pk, variant_pk=variant.pk) ctx = {'form': form, 'product': product, 'variant': variant, 'stock': stock} return TemplateResponse( request, 'dashboard/product/stock/form.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 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_details(request, product_pk, variant_pk): product = get_object_or_404(Product, pk=product_pk) qs = product.variants.prefetch_related( 'stock__location', 'product__product_class__variant_attributes__values') variant = get_object_or_404(qs, pk=variant_pk) # If the product class of this product assumes no variants, redirect to # product details page that has special UI for products without variants. if not product.product_class.has_variants: return redirect('dashboard:product-detail', pk=product.pk) stock = variant.stock.all() images = variant.images.all() ctx = {'images': images, 'product': product, 'stock': stock, 'variant': variant} return TemplateResponse( request, 'dashboard/product/product_variant/detail.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 attribute_edit(request, pk=None): if pk: attribute = get_object_or_404(ProductAttribute, pk=pk) else: attribute = ProductAttribute() form = forms.ProductAttributeForm(request.POST or None, instance=attribute) formset = forms.AttributeChoiceValueFormset( request.POST or None, request.FILES or None, instance=attribute) if all([form.is_valid(), formset.is_valid()]): attribute = form.save() formset.save() msg = pgettext_lazy( 'Dashboard message', 'Updated attribute') if pk else pgettext_lazy( 'Dashboard message', 'Added attribute') messages.success(request, msg) return redirect('dashboard:product-attribute-detail', pk=attribute.pk) ctx = {'attribute': attribute, 'form': form, 'formset': formset} return TemplateResponse( request, 'dashboard/product/product_attribute/form.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 anonymous_user_shipping_address_view(request, checkout): """Display the shipping step for a user who is not logged in.""" address_form, preview = get_address_form( request.POST or None, country_code=request.country.code, autocomplete_type='shipping', initial={'country': request.country.code}, instance=checkout.shipping_address) user_form = AnonymousUserShippingForm( not preview and request.POST or None, initial={'email': checkout.email} if not preview else request.POST.dict()) if all([user_form.is_valid(), address_form.is_valid()]): checkout.shipping_address = address_form.instance checkout.email = user_form.cleaned_data['email'] return redirect('checkout:shipping-method') return TemplateResponse( request, 'checkout/shipping_address.html', context={ 'address_form': address_form, 'user_form': user_form, 'checkout': checkout})
def summary_with_shipping_view(request, checkout): """Display order summary with billing forms for a logged in user. Will create an order if all data is valid. """ if request.user.is_authenticated: additional_addresses = request.user.addresses.all() else: additional_addresses = Address.objects.none() address_form, addresses_form, address = get_billing_forms_with_shipping( request.POST or None, additional_addresses, checkout.billing_address or Address(country=request.country), checkout.shipping_address) if address is not None: checkout.billing_address = address return handle_order_placement(request, checkout) return TemplateResponse( request, 'checkout/summary.html', context={ 'addresses_form': addresses_form, 'address_form': address_form, 'checkout': checkout, 'additional_addresses': additional_addresses})
def anonymous_summary_without_shipping(request, checkout): """Display order summary with billing forms for an unauthorized user. Will create an order if all data is valid. """ user_form = AnonymousUserBillingForm( request.POST or None, initial={'email': checkout.email}) billing_address = checkout.billing_address if billing_address: address_form, preview = get_address_form( request.POST or None, country_code=billing_address.country.code, autocomplete_type='billing', instance=billing_address) else: address_form, preview = get_address_form( request.POST or None, country_code=request.country.code, autocomplete_type='billing', initial={'country': request.country}) if all([user_form.is_valid(), address_form.is_valid()]) and not preview: checkout.email = user_form.cleaned_data['email'] checkout.billing_address = address_form.instance return handle_order_placement(request, checkout) return TemplateResponse( request, 'checkout/summary_without_shipping.html', context={ 'user_form': user_form, 'address_form': address_form, 'checkout': checkout})
def create_password(request, token): if request.user.is_authenticated: return redirect('order:details', token=token) order = get_object_or_404(Order, token=token) email = order.user_email form_data = request.POST.copy() if form_data: form_data.update({'email': email}) register_form = PasswordForm(form_data or None) if User.objects.filter(email=email).exists(): login_form = LoginForm(initial={'login': email}) else: login_form = None if register_form.is_valid(): register_form.save() password = register_form.cleaned_data.get('password') user = auth.authenticate(request=request, email=email, password=password) auth.login(request, user) attach_order_to_user(order, user) return redirect('order:details', token=token) ctx = {'form': register_form, 'email': email, 'order': order, 'login_form': login_form} return TemplateResponse(request, 'order/create_password.html', ctx)
def post(self, request, *args, **kwargs): form = self.password_reset_form(request.POST) if form.is_valid(): opts = { 'use_https': request.is_secure(), 'token_generator': self.password_reset_token_generator, 'email_template_name': self.password_reset_email_template, 'request': request, 'domain_override': request.get_host() } if self.password_reset_from_email: opts['from_email'] = self.password_reset_from_email if self.password_reset_subject_template: opts['subject_template_name'] = self.password_reset_subject_template form.save(**opts) context = super(ResetPasswordSendView, self).get_context() return TemplateResponse(request, self.password_reset_done_template, context, current_app=self.admin_site.name) else: return self.get(request, form=form)
def password_reset_done(request, template_name='registration/password_reset_done.html', extra_context=None): warnings.warn("The password_reset_done() view is superseded by the " "class-based PasswordResetDoneView().", RemovedInDjango21Warning, stacklevel=2) context = { 'title': _('Password reset sent'), } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context) # Doesn't need csrf_protect since no-one can guess the URL
def index(self, request, extra_context=None): """ Displays the main admin index page, which lists all of the installed apps that have been registered in this site. """ app_list = self.get_app_list(request) context = dict( self.each_context(request), title=self.index_title, app_list=app_list, ) context.update(extra_context or {}) request.current_app = self.name return TemplateResponse(request, self.index_template or 'admin/index.html', context)
def post(self, request, *args, **kwargs): form = self.password_reset_form(request.POST) if form.is_valid(): opts = { 'use_https': request.is_secure(), 'token_generator': self.password_reset_token_generator, 'email_template_name': self.password_reset_email_template, 'request': request, 'domain_override': request.get_host() } if self.password_reset_from_email: opts['from_email'] = self.password_reset_from_email if self.password_reset_subject_template: opts['subject_template_name'] = self.password_reset_subject_template form.save(**opts) context = super(ResetPasswordSendView, self).get_context() return TemplateResponse(request, self.password_reset_done_template, context) else: return self.get(request, form=form)
def password_reset(request): if request.method == "POST": form = PasswordResetForm(request.POST, ) if form.is_valid(): email = form.cleaned_data.get('email') user = User.objects.get(email=email) msg = tokens.generate_pw_reset_email(user, request) msg.send() return HttpResponseRedirect(reverse('password_reset_done')) else: form = PasswordResetForm() context = { 'form': form, } return TemplateResponse(request, 'password_reset_form.html', context)
def password_reset_confirm(request, uid, token): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ try: uid = force_text(urlsafe_base64_decode(uid)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): return TemplateResponse(request, 'password_reset_confirm.html', {'validlink': False}) if password_reset_token.check_token(user, token): if request.method == 'POST': form = SetPasswordForm(request.POST) if form.is_valid(): form.save(user) return HttpResponseRedirect(reverse('password_reset_complete')) form = SetPasswordForm() else: return TemplateResponse(request, 'password_reset_confirm.html', {'validlink': False}) return TemplateResponse(request, 'password_reset_confirm.html', {'validlink': True, 'form': form})
def invite(request, poll_url): current_poll = get_object_or_404(Poll, url=poll_url) error_msg = "" if request.method == 'POST': if not current_poll.can_edit(request.user, request): error_msg = "Not allowed to edit" else: if 'resend_all' in request.POST: for invitation in current_poll.invitation_set: invitation.send(request) return redirect('poll_settings', current_poll.url) elif 'resend' in request.POST: invitation_id = request.POST.get('resend', None) if invitation_id: invitation = get_object_or_404(Invitation, pk=invitation_id) invitation.send(request) return redirect('invitations', current_poll.url) elif 'delete' in request.POST: invitation_id = request.POST.get('delete', None) if invitation_id: invitation = get_object_or_404(Invitation, id=invitation_id) invitation.delete() return redirect('invitations', current_poll.url) return TemplateResponse(request, 'invitations/Invitation.html', { 'poll': current_poll, })
def index(request): group = request.user.groups.order_by('name').first() if group: return redirect('groups_show', group.name) else: return TemplateResponse(request, 'groups/groups_base.html')
def edit_choicevalues(request, poll_url): current_poll = get_object_or_404(Poll, url=poll_url) choiceval_select = None if not current_poll.can_edit(request.user, request): return redirect('poll', poll_url) form = ChoiceValueForm() if request.method == 'POST': if 'delete' in request.POST: choiceval_id = request.POST.get('delete', None) if choiceval_id: choiceval = get_object_or_404(ChoiceValue, id=choiceval_id) choiceval.deleted = True choiceval.save() return redirect('poll_editchoicevalues', current_poll.url) if 'restore' in request.POST: choiceval_id = request.POST.get('restore', None) if choiceval_id: choiceval = get_object_or_404(ChoiceValue, id=choiceval_id) choiceval.deleted = False choiceval.save() return redirect('poll_editchoicevalues', current_poll.url) elif 'edit' in request.POST: choiceval_id = request.POST.get('edit', None) if choiceval_id: choiceval_select = get_object_or_404(ChoiceValue, id=choiceval_id) form = ChoiceValueForm(instance=choiceval_select) return TemplateResponse(request, 'poll/choicevalue.html', { 'poll': current_poll, 'form': form, 'choiceval_select': choiceval_select, 'choice_values': ChoiceValue.objects.filter(poll=current_poll) })
def edit_choicevalues_create(request, poll_url): current_poll = get_object_or_404(Poll, url=poll_url) if not current_poll.can_edit(request.user, request): return redirect('poll', poll_url) form = ChoiceValueForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] color = form.cleaned_data['color'] icon = form.cleaned_data['icon'] weight = form.cleaned_data['weight'] current_id = request.POST.get('choiceval_id', None) if current_id: current_choiceval = get_object_or_404(ChoiceValue, id=current_id, poll=current_poll) current_choiceval.title = title current_choiceval.color = color current_choiceval.icon = icon current_choiceval.weight = weight current_choiceval.save() else: choice_val = ChoiceValue(title=title, icon=icon, color=color, weight=weight, poll=current_poll) choice_val.save() else: choiceval_id = request.POST.get('choiceval_id', None) if choiceval_id: choiceval_select = get_object_or_404(ChoiceValue, id=choiceval_id) else: choiceval_select = None return TemplateResponse(request, 'poll/choicevalue.html', { 'poll': current_poll, 'form': form, 'choiceval_select': choiceval_select, }) return redirect('poll_editchoicevalues', current_poll.url)