简体   繁体   English

如何使用ChoiceField为Model FloatField属性Django自定义ModelForm

[英]How to customize a ModelForm with ChoiceField for a Model FloatField attribute Django

I have a model called Invoice with the following attribute (and other stuff): 我有一个名为Invoice的模型,具有以下属性(和其他内容):

class Invoice(models.Model):
    tax = models.FloatField()

And a model called Tax: 还有一个称为Tax的模型:

class Tax(models.Model):
    name = models.CharField(max_length=20)
    value = models.FloatField()
    creation_date = models.DateTimeField(auto_now_add=True)
    description = models.CharField(max_length=50, blank=True)

    def __unicode__(entry):
        return str(entry.id) + " - " + entry.name + " (%.1f" % (entry.value) + "%)"

On my ModelForm I have: 在我的ModelForm上,我有:

class InvoiceForm(ModelForm):
    class Meta:
        model = Invoice
        fields = '__all__'
        widgets = {
            'due_date': forms.TextInput(attrs={'class': 'form-control'}),
            'due_date': DateTimePicker(options={"format": "DD/MM/YYYY","pickTime": False}),
            'tax': forms.ChoiceField(choices=(Tax))
    }

What I want is to generate a ModelForm for this class replacing the FloatField for a ChoiceField with the values from the class Tax. 我想要为该类生成一个ModelForm,用类Tax的值替换ChoiceField的FloatField。 And when the form is submitted I would get the value of the tax (tax.value) and set to invoice.tax, since both are the same data type. 提交表单后,我将获得tax的值(tax.value)并将其设置为invoice.tax,因为两者都是相同的数据类型。

I was expecting to do something like when we have a M2M relation, that you have the dropbox. 我原本希望做类似M2M关系的事情,即您拥有保管箱。 The problem in my project is that if the value of the Tax is modified or even deleted, I will have problems with my already generated invoices. 我的项目中的问题是,如果“税”的值被修改甚至删除,那么我已经生成的发票就会出现问题。

I could do some workaround and make it work when the page is submitted, but I don't want to do that. 我可以采取一些解决方法,并在提交页面时使其正常工作,但是我不想这样做。 This is my first project with Django and I would like to learn all its potential. 这是我与Django合作的第一个项目,我想学习它的所有潜力。

You might not need a ModelForm but a normal Form because what you get from the InvoiceForm is a Tax object, which doesn't fit in your Invoice model. 您可能不需要ModelForm但需要普通的Form因为从InvoiceForm获得的是Tax对象,该对象不适合您的Invoice模型。

What you can do is define a form with every field except tax for Invoice , then for the tax field you use form.ModelChoiceField : 你可以做的是定义一个形式每场除了taxInvoice ,那么对于tax使用领域form.ModelChoiceField

class InvoiceForm(Form):
    # define all your fields, I put some dummy fields here
    field1 = CharField()
    field2 = TextField()
    # etc
    tax = ModelChoiceField(queryset=Tax.objects.all())

Then in your views.py, get the values manually and construct your Invoice : 然后在您的views.py中,手动获取值并构建您的Invoice

form = InvoiceForm(request.POST)
if form.is_valid():
    field1 = form.cleaned_data['field1']
    field2 = form.cleaned_data['field2']
    tax_obj = form.cleaned_data['tax']
    # create your invoice here
    new_invoice = Invoice.objects.create(field1=field1,
                                         field2 = field2,
                                         tax=tax_obj.value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM