Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!