Ilya Bibik
Ilya Bibik

Reputation: 4124

How to combine dynamically created fields with standard django form?

I use simple django form

class MassPaymentForm(forms.ModelForm):


    class Meta:
        model = LeasePayment

        fields = ['payment_type', 'is_deposit',  'amount', 'method', 'payment_date', 'description'] 

On my template I have created few chained dropdowns using AJAX

      <form method="POST"  class="form" action="" method="get">
        <div class="form-group">
            {% csrf_token %}

            <br><br>
            <b>Building:</b><br>
                <select name="building" id="building" onchange="getunit();">
  <option id="-1">Select building</option>
</select>


<br>
<b>Unit:</b><br>
<select name="unit" id="unit" onchange="getlease();">
  <option id="-1">Select unit</option>
</select>
  <br>
<b>Lease:</b><br>
 <select name="lease" id="lease" onchange="getleaseterm()">
  <option id="-1">Select lease</option>
</select>
  <br>
<b>Term:</b><br>
   <select name="leaseterm" id="leaseterm">
  <option id="-1">Select lease term</option>
</select> 
            {{ form|crispy}}



        {{ form.media }}

            <BR><BR>
            <button type="submit" class="btn btn-primary btn-primary">Save</button>
          </div>
      </form>

I need 'lease' and 'leaseterm' to be part of my form when it saves since they are mandatory fields in the model.. How can I include those AJAx dynamically generated dropdown as part of my Django form?

Upvotes: 0

Views: 164

Answers (1)

dirkgroten
dirkgroten

Reputation: 20692

Just add them to your form directly, if they're part of your model. Or if the model fields default to something that doesn't work for validation, override them directly as standard form fields. Since you're rendering them explicitly in your HTML, you don't want them to render. So you should add a css class to the widget to hide them from the browser (remove them entirely with javascript), otherwise you'll have two input fields with the same name.

class MassPaymentForm(forms.ModelForm):

    unit = CharField(widget=HiddenInput(attrs={'class': 'to-remove'})
    lease = CharField(widget=HiddenInput(attrs={'class': 'to-remove'})
    leaseterm = CharField(required=False, widget=HiddenInput(attrs={'class': 'to-remove'})  # just as an example

    class Meta:
         # rest of Meta class here

Upvotes: 1

Related Questions