简体   繁体   中英

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: 在此处输入图片说明

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

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
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM