def product_class_create(request):
product_class = ProductClass()
form = forms.ProductClassForm(request.POST or None,
instance=product_class)
if form.is_valid():
product_class = form.save()
msg = pgettext_lazy(
'Dashboard message', 'Added product type %s') % product_class
messages.success(request, msg)
return redirect('dashboard:product-class-list')
ctx = {'form': form, 'product_class': product_class}
return TemplateResponse(
request,
'dashboard/product/product_class/form.html',
ctx)
python类pgettext_lazy()的实例源码
def product_create(request, class_pk):
product_class = get_object_or_404(ProductClass, pk=class_pk)
create_variant = not product_class.has_variants
product = Product()
product.product_class = product_class
product_form = forms.ProductForm(request.POST or None, instance=product)
if create_variant:
variant = ProductVariant(product=product)
variant_form = forms.ProductVariantForm(
request.POST or None, instance=variant, prefix='variant')
variant_errors = not variant_form.is_valid()
else:
variant_form = None
variant_errors = False
if product_form.is_valid() and not variant_errors:
product = product_form.save()
if create_variant:
variant.product = product
variant_form.save()
msg = pgettext_lazy(
'Dashboard message', 'Added product %s') % product
messages.success(request, msg)
return redirect('dashboard:product-detail', pk=product.pk)
ctx = {
'product_form': product_form, 'variant_form': variant_form,
'product': product}
return TemplateResponse(request, 'dashboard/product/form.html', ctx)
def product_delete(request, pk):
product = get_object_or_404(Product, pk=pk)
if request.method == 'POST':
product.delete()
messages.success(
request,
pgettext_lazy('Dashboard message', 'Deleted product %s') % product)
return redirect('dashboard:product-list')
return TemplateResponse(
request,
'dashboard/product/modal/confirm_delete.html',
{'product': product})
def product_image_delete(request, product_pk, img_pk):
product = get_object_or_404(Product, pk=product_pk)
image = get_object_or_404(product.images, pk=img_pk)
if request.method == 'POST':
image.delete()
messages.success(
request,
pgettext_lazy(
'Dashboard message',
'Deleted image %s') % image.image.name)
return redirect('dashboard:product-image-list', product_pk=product.pk)
return TemplateResponse(
request,
'dashboard/product/product_image/modal/confirm_delete.html',
{'product': product, 'image': image})
def attribute_delete(request, pk):
attribute = get_object_or_404(ProductAttribute, pk=pk)
if request.method == 'POST':
attribute.delete()
messages.success(
request,
pgettext_lazy(
'Dashboard message',
'Deleted attribute %s') % (attribute.name,))
return redirect('dashboard:product-attributes')
return TemplateResponse(
request,
'dashboard/product/product_attribute/modal/confirm_delete.html',
{'attribute': attribute})
def stock_location_delete(request, location_pk):
location = get_object_or_404(StockLocation, pk=location_pk)
stock_count = location.stock_set.count()
if request.method == 'POST':
location.delete()
messages.success(
request, pgettext_lazy(
'Dashboard message for stock location',
'Deleted location %s') % location)
return redirect('dashboard:product-stock-location-list')
ctx = {'location': location, 'stock_count': stock_count}
return TemplateResponse(
request,
'dashboard/product/stock_location/modal/confirm_delete.html',
ctx)
def clean_location(self):
location = self.cleaned_data['location']
if (
not self.instance.pk and
self.variant.stock.filter(location=location).exists()):
self.add_error(
'location',
pgettext_lazy(
'stock form error',
'Stock item for this location and variant already exists'))
return location
def clean(self):
data = super(ProductClassForm, self).clean()
has_variants = self.cleaned_data['has_variants']
product_attr = set(self.cleaned_data['product_attributes'])
variant_attr = set(self.cleaned_data['variant_attributes'])
if not has_variants and len(variant_attr) > 0:
msg = pgettext_lazy(
'Product class form error',
'Product variants are disabled.')
self.add_error('variant_attributes', msg)
if len(product_attr & variant_attr) > 0:
msg = pgettext_lazy(
'Product class form error',
'A single attribute can\'t belong to both a product '
'and its variant.')
self.add_error('variant_attributes', msg)
if self.instance.pk:
variants_changed = not (self.fields['has_variants'].initial ==
has_variants)
if variants_changed:
query = self.instance.products.all()
query = query.annotate(variants_counter=Count('variants'))
query = query.filter(variants_counter__gt=1)
if query.exists():
msg = pgettext_lazy(
'Product class form error',
'Some products of this type have more than '
'one variant.')
self.add_error('has_variants', msg)
return data
def __init__(self, *args, **kwargs):
self.product_attributes = []
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['categories'].widget.attrs['data-placeholder'] = (
pgettext_lazy('Product form placeholder', 'Search'))
product_class = self.instance.product_class
self.product_attributes = product_class.product_attributes.all()
self.product_attributes = self.product_attributes.prefetch_related(
'values')
self.prepare_fields_for_attributes()
def release_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)
form = ReleasePaymentForm(request.POST or None, payment=payment)
if form.is_valid() and form.release():
msg = pgettext_lazy('Dashboard message', 'Released payment')
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/release.html', ctx,
status=status)
def orderline_change_quantity(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)
variant = get_object_or_404(
ProductVariant, sku=item.product_sku)
form = ChangeQuantityForm(
request.POST or None, instance=item, variant=variant)
status = 200
old_quantity = item.quantity
if form.is_valid():
with transaction.atomic():
form.save()
msg = pgettext_lazy(
'Dashboard message related to an order line',
'Changed quantity for product %(product)s from'
' %(old_quantity)s to %(new_quantity)s') % {
'product': item.product, 'old_quantity': old_quantity,
'new_quantity': item.quantity}
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, 'object': item, 'form': form}
template = 'dashboard/order/modal/change_quantity.html'
return TemplateResponse(request, template, ctx, status=status)
def orderline_split(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 = MoveItemsForm(request.POST or None, item=item)
line_pk = None
if item:
line_pk = item.pk
status = 200
if form.is_valid():
old_group = item.delivery_group
how_many = form.cleaned_data['quantity']
with transaction.atomic():
target_group = form.move_items()
if not old_group.pk:
old_group = pgettext_lazy(
'Dashboard message related to a delivery group',
'removed group')
msg = pgettext_lazy(
'Dashboard message related to delivery groups',
'Moved %(how_many)s items %(item)s from %(old_group)s'
' to %(new_group)s') % {
'how_many': how_many, 'item': item, 'old_group': old_group,
'new_group': target_group}
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, 'object': item, 'form': form, 'line_pk': line_pk}
template = 'dashboard/order/modal/split_order_line.html'
return TemplateResponse(request, template, ctx, status=status)
def clean(self):
if self.payment.status != PaymentStatus.PREAUTH:
raise forms.ValidationError(
pgettext_lazy(
'Payment form error',
'Only pre-authorized payments can be captured'))
def capture(self):
amount = self.cleaned_data['amount']
try:
self.payment.capture(amount.gross)
except (PaymentError, ValueError) as e:
self.add_error(
None,
pgettext_lazy(
'Payment form error',
'Payment gateway error: %s') % e.message)
return False
return True
def refund(self):
amount = self.cleaned_data['amount']
try:
self.payment.refund(amount.gross)
except (PaymentError, ValueError) as e:
self.add_error(
None,
pgettext_lazy(
'Payment form error',
'Payment gateway error: %s') % e.message)
return False
return True
def clean(self):
if self.payment.status != PaymentStatus.PREAUTH:
raise forms.ValidationError(
pgettext_lazy(
'Payment form error',
'Only pre-authorized payments can be released'))
def release(self):
try:
self.payment.release()
except (PaymentError, ValueError) as e:
self.add_error(
None,
pgettext_lazy(
'Payment form error',
'Payment gateway error: %s') % e.message)
return False
return True
def get_delivery_group_choices(self):
group = self.item.delivery_group
groups = group.order.groups.exclude(pk=group.pk).exclude(
status='cancelled')
choices = [(self.NEW_SHIPMENT, pgettext_lazy(
'Delivery group value for `target_group` field',
'New shipment'))]
choices.extend([(g.pk, str(g)) for g in groups])
return choices
def __init__(self, *args, **kwargs):
super(ShipGroupForm, self).__init__(*args, **kwargs)
self.fields['tracking_number'].widget.attrs.update(
{'placeholder': pgettext_lazy(
'Ship group form field placeholder',
'Parcel tracking number')})
def clean(self):
data = super(CancelOrderForm, self).clean()
if not self.order.can_cancel():
raise forms.ValidationError(
pgettext_lazy(
'Cancel order form error',
'This order can\'t be cancelled'))
return data