Dynamic Modelform - Django

Asked

Viewed 343 times

1

Hello! I am using Modelform from Django 2.2, and I need to leave the dynamic form. The "Number of installments" field should only appear when the Payment Method is credit.

At first I tried to do with JS:

function exibir_ocultar(){
var valor = $("#id_metodo_de_pagamento").val();

if(valor == 'credito'){
     $("#id_quantidade_de_parcelas").show();

 } else {
     $("#id_quantidade_de_parcelas").hide();
 } };

I came across the problem of not being able to edit select to call the JS function, since Django itself generates the form. Follow the code used to generate the form:

           {% bootstrap_messages %}
            <form action="{% url 'cadastro' %}" method="POST" class="form" autocomplete="off" >
                {% csrf_token %}
                {% bootstrap_form form %}
                {% buttons %}
                    <button type="submit" href="{% url 'index' %}" class= "btn btn-success">Salvar </button>
                    <button type="submit" href="{% url 'index' %}" name="exit" value="True" class= "btn btn-dark">Salvar e fechar </button>                                
               {% endbuttons %}
            </form>

What is the best way to accomplish this action?

1 answer

3


So boys, for those of you with the same doubt and don’t want to depend on these losers in his life outside of the street that mark the question as "no effort", follows what I used to apply this idea in my project study (STUDY, therefore it means that I do not have much notion of how or what to research and explain my doubts, rsrs)

In Django there are widgets, which makes it possible to insert HTML input elements. I went to the project’s "Forms.py" file, and within the Meta class, where the form’s Fields are specified, we were able to define the HTML elements from a python dictionary.

from django import forms
from .models import Compra

class CompraModelForm(forms.ModelForm):
class Meta:
    model = Compra
    fields = ['nome_da_compra', 'preco', 'data_da_compra', 'local_da_compra', 'metodo_de_pagamento', 'quantidade_de_parcelas']
    widgets  =  { 'metodo_de_pagamento': forms.Select(attrs = {'onchange' : "exibir_ocultar();"}) }

After that, the idea of displaying and hiding the fields works perfectly. I used the JS script inside the Static folder and imported it into my HTML through the script tag. Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.