How can I add a field in a form from another distinct model in django?

75 Views Asked by At

I have a form which is based in a model X which has some attribute fields, and I want to add a field, which is not from that model (the field is from another distinct model, in fact), in the same form. How can I add it?

1

There are 1 best solutions below

0
On BEST ANSWER

Just add another model form or form class instance to your view:

class YourModelForm(forms.ModelForm):

    class Meta:
        model = YourModel


class YourOtherForm(forms.Form):

    non_model_field = forms.CharField(max_length=100)


# view

def your_view(request):

    your_model_form = YourModelForm(request.POST or None)
    your_other_form = YourOtherForm(request.POST or None)

    if request.method == 'POST' and your_model_form.is_valid and your_other_form.is_valid:
        your_model_form.save()

        # handle your_other_form, as forms.Form doesn't have a built-in .save

    return render(request, 'your_template.html',
        {'your_model_form': your_model_form, 'your_other_form': your_other_form})


# template

<form action="." method="post" enctype="application/x-www-form-urlencoded">
    <ul>
        {{ your_model_form.as_ul }}
        {{ your_other_form.as_ul }}
    </ul>
    <button type="submit">Submit</button>
</form>

Django doesn't care how many forms you have in your view.