[Fixed]-How to customize a ModelForm with ChoiceField for a Model FloatField attribute 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.

What you can do is define a form with every field except tax for Invoice, then for the tax field you use 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:

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,

Leave a comment