我想在 oscar 的文档之后从仪表板添加多个经销商支持:
您需要强制为每个产品创建一个 StockRecord。创建产品时,Stockrecord.partner 被设置为 self.request.user.partner(必要时创建),因此建立了连接
我不知道如何强制创建 StockRecord。oscar 有一个仪表板取代了 django 管理员,这是用于创建/更新产品的视图的摘录(第一行):
class ProductCreateUpdateView(generic.UpdateView):
"""
Dashboard view that bundles both creating and updating single products.
Supports the permission-based dashboard.
"""
template_name = 'dashboard/catalogue/product_update.html'
model = Product
context_object_name = 'product'
form_class = ProductForm
category_formset = ProductCategoryFormSet
image_formset = ProductImageFormSet
recommendations_formset = ProductRecommendationFormSet
stockrecord_formset = StockRecordFormSet
因此,产品创建视图将显示 StockRecord 表单集,但我可以在不创建 StockRecord 对象的情况下创建/更新产品。发生这种情况时,我想显示一条错误消息。
StockRecord 表格/表格集:
class StockRecordForm(forms.ModelForm):
def __init__(self, product_class, *args, **kwargs):
super(StockRecordForm, self).__init__(*args, **kwargs)
# If not tracking stock, we hide the fields
if not product_class.track_stock:
del self.fields['num_in_stock']
del self.fields['low_stock_threshold']
else:
self.fields['price_excl_tax'].required = True
self.fields['num_in_stock'].required = True
class Meta:
model = StockRecord
exclude = ('product', 'partner', 'num_allocated')
BaseStockRecordFormSet = inlineformset_factory(
Product, StockRecord, form=StockRecordForm, extra=1)
class StockRecordFormSet(BaseStockRecordFormSet):
def __init__(self, product_class, *args, **kwargs):
self.product_class = product_class
super(StockRecordFormSet, self).__init__(*args, **kwargs)
def _construct_form(self, i, **kwargs):
kwargs['product_class'] = self.product_class
return super(StockRecordFormSet, self)._construct_form(
i, **kwargs)
StockRecord 模型(摘录):
class AbstractStockRecord(models.Model):
product = models.ForeignKey(
'catalogue.Product', related_name="stockrecords",
verbose_name=_("Product"))
partner = models.ForeignKey(
'partner.Partner', verbose_name=_("Partner"),
related_name='stockrecords')
partner_sku = models.CharField(_("Partner SKU"), max_length=128)
price_currency = models.CharField(
_("Currency"), max_length=12, default=settings.OSCAR_DEFAULT_CURRENCY)
price_excl_tax = models.DecimalField(
_("Price (excl. tax)"), decimal_places=2, max_digits=12,
blank=True, null=True)
price_retail = models.DecimalField(
_("Price (retail)"), decimal_places=2, max_digits=12,
blank=True, null=True)