执行相关的模型创建

时间:2014-01-29 15:32:48

标签: django django-oscar

我想在奥斯卡documentation之后的仪表板中添加多个经销商支持:

  

您需要强制为每个产品创建StockRecord。   创建产品时,Stockrecord.partner将被设置   to 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)

1 个答案:

答案 0 :(得分:1)

您要做的是确保在保存主表单时至少提交了1个有效的表单集?