Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
Is there a way to make a form dynamic in django

I'm trying to make a dynamic dropdown list in the Admin Panel. It should show all the fields from a certain model.

Here is the snippet of my code:

JS_FUNCTION = """
obj = document.getElementById('id_field_name');
for (let i = 0, len = test.length; i < len; i++) {
    var opt = document.createElement('option');
    opt.value = test[i];
    opt.innerHTML = test[i];
    obj.appendChild(opt);
} 
"""


def set_queryset(value):
    # model = SyncModel.objects.get(id=value)
    # return model.get_fields()
    return ["a", "b", "c", "d"]


class WhitelistForm(forms.ModelForm):
    sync_model = forms.ModelChoiceField(
        queryset=SyncModel.objects.all(),
        widget=forms.Select(
            attrs={
                "onchange": f'console.log(value); var test = {set_queryset("value")}; {JS_FUNCTION}',
                "required": True,
            }
        ),
    )
    field_name = forms.ChoiceField(
        choices=(),
    )

    class Meta:
        model = WhitelistModel
        fields = "__all__"

The problem is, I need to return the fields from the model. However, when I pass the 'value' as a parameter for the python function, it doesn't send the id the is printed on the console.log.

Console Log output: enter image description here

I'd like to know if there is a way to make the model dynamic only on the form file.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

One way you could accomplish your goal is to write a function that returns the names of the fields in your model, with the desired values for the options. You could use a forms.ChoiceField and set choices=getFields(). Remember that choices takes a tuple of tuples, so that is what you must return from getFields().

from app.model import myModel

def getFields():
all_fields = myModel._meta.fields
*Do something to extract the names in the format you want*
*Create a list of vals to zip to the names*
data = tuple(zip(vals, all_fields))
return data
 
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda