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,
})
python类success()的实例源码
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 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,
})