【问题标题】:Django - How can i assign a value to a object using a formset but in a viewDjango - 我如何使用表单集但在视图中为对象赋值
【发布时间】:2017-07-30 23:17:33
【问题描述】:

(对不起我的英语不好) 我需要向我从表单集中排除的对象字段添加一个值。我喜欢在视图中自动分配它。 (我无法修改模型以添加 def save 方法并使其存在,因为是第三方应用程序模型)

这是模型

class Tax(models.Model):
    """A tax (type+amount) for a specific Receipt."""

    tax_type = models.ForeignKey(
        TaxType,
        verbose_name=_('tax type'),
        on_delete=models.PROTECT,
    )
    description = models.CharField(
        _('description'),
        max_length=80,
    )
    base_amount = models.DecimalField(
        _('base amount'),
        max_digits=15,
        decimal_places=2,
    )
    aliquot = models.DecimalField(
        _('aliquot'),
        max_digits=5,
        decimal_places=2,
    )
    amount = models.DecimalField(
        _('amount'),
        max_digits=15,
        decimal_places=2,
    )

    receipt = models.ForeignKey(
        Receipt,
        related_name='taxes',
        on_delete=models.PROTECT,
    )

    def compute_amount(self):
        """Auto-assign and return the total amount for this tax."""
        self.amount = self.base_amount * self.aliquot / 100
        return self.amount

    class Meta:
        verbose_name = _('tax')
        verbose_name_plural = _('taxes')

这是表单和表单集

class TaxForm(forms.ModelForm):
    class Meta:
        model = Tax
        fields = [
            'tax_type',
            'description',
            'base_amount',
            'aliquot',
        ]

ReceiptTaxFormset = inlineformset_factory(
    Receipt,
    Tax,
    form=TaxForm,
    extra=0,
    can_delete=False,
)

这是我处理表单集的视图部分

if form.is_valid() and entryFormset.is_valid() and taxFormset.is_valid():
            receipt = form.save(commit=False)
            # Tomamos el punto de venta de la sucursal y lo asignamos
            pos = request.user.userprofile.branch_office.point_of_sales
            receipt.point_of_sales = pos

            receipt.document_number = client.dni_cuit
            # Controlamos si el dni o cuit tiene 11 caracteres
            # Si los tiene asigna CUIT al típo de documento
            if len(client.dni_cuit) == 11:
                document_type = DocumentType.objects.get(id=1)
                receipt.document_type = document_type
            else:
                document_type = DocumentType.objects.get(id=10)
                receipt.document_type = document_type

            # Tomamos los valores de las lineas del comprobante
            # y generamos los totales para asentar en el comprobante
            total_amount = 0
            for f in entryFormset:
                cd = f.cleaned_data
                qty = cd.get('quantity')
                price = cd.get('unit_price')
                vat = cd.get('vat')
                subtotal = qty * price
                total_amount = total_amount + subtotal

            for t in taxFormset:
                cd = t.cleaned_data
                ba = cd.get('base_amount')
                al = cd.get('aliquot')
                ta = ba * al / 100
                total_amount = total_amount + ta

            # Asignamos el monto total a total_ammount
            # y a net_taxed para factura tipo C ya que es igual
            receipt.total_amount = total_amount
            receipt.net_taxed = total_amount

            # Asignamos 0 para Factura tipo C a los campos no necesarios
            receipt.net_untaxed = 0
            receipt.exempt_amount = 0

            # Guardamos el comprobante y las lineas del mismo
            receipt.save()
            entryFormset.save()
            taxFormset.save()

我需要做的是在 taxFormset 中,对于我从表格中获得的每项税款,将金额分配给对象 ta = ba * al / 100

谢谢!

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    inlineformset_factory 位于使用实例的 modelformset_factory 之上

    我很想看看它给你带来了什么错误,或者它是否没有保存,但也许你错过了这样的东西。

            receipt.instance.total_amount = total_amount
            receipt.instance.net_taxed = total_amount
    
            # Asignamos 0 para Factura tipo C a los campos no necesarios
            receipt.instance.net_untaxed = 0
            receipt.instance.exempt_amount = 0
    
            # Guardamos el comprobante y las lineas del mismo
            receipt.save()
            entryFormset.save()
            taxFormset.save()
    

    【讨论】:

    • 对不起,也许我没有很好地解释我需要什么。我没有任何错误,我需要做其他事情。如您所见,我在模型税收中具有“金额”字段,当我获取taxFormset中的所有值时,我需要能够在视图中设置金额的值...为税收的每一行分配正确的数量!
    • 我仍然不确定你想要什么,但我会尽力帮助我理解。 - 金额的值似乎是为每项税设置的计算值。您需要在表单集中的每个表单周围循环以应用该值?,如果这是您想要做的,您可以在视图中循环表单集,或者如果您还想为表单集级别清理或保存定义 BaseModelFormSet。 docs.djangoproject.com/en/1.11/topics/forms/modelforms/…
    • 感谢您在不了解我的情况下尝试帮助我。我将尝试用一个示例向您解释,当我有一个表单时,例如 ModelForm,并且在表单中我没有放置对象的强制属性,在视图中,我使用 article = form.save( commit=false) 并且我放了 artile.amount = XXXXX + XXXXX 例如,对于一个对象,这项工作完美,但在一个表单集中我有很多对象要保存,我的问题是我如何为每个对象分配该值表单集中的对象之一。 (我想你现在可以理解我需要什么了。
    • 我知道您可以像使用普通表单一样执行它们,唯一不同的是您需要遍历该表单集。但是我你也可以使用 BaseModelFormSet ,你可以在 form.py 中定义它,并在你的 formset 初始化中分配它,就像现在当每个表单都经过验证时,基本 modelformset 将是最后调用,你可以做同样的事情,比如 def clean(self): for form in self.form 而不是将你想要的值赋给这个表单对象
    猜你喜欢
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    相关资源
    最近更新 更多