Search code examples
djangoformsdjango-formsjsonschemapython-jsonschema

How to create dynamic form using JSONSchemaField based on ID passed from the form request in Django?


The form is rendering properly if I give ID as a static value in forms.py, it wont render properly when I use the ID that I got from form call

views.py

def assetAddJsonView(request,pk):
    form = AssetAddjsonForm(id = pk)
    context = {
        'form': form
    }
    return render(request, 'asset_add_json.html', context)

forms.py

from django_jsonforms.forms import JSONSchemaField

class AssetAddjsonForm(Form):
    def __init__(self, *args, **kwargs):
       self.request = kwargs.pop('id')
       super(AssetAddjsonForm, self).__init__(*args, **kwargs)

    type_json_schema = Types.objects.values_list('details').get(id=1)   # details contains schema object
    type_json_schema = list(type_json_schema)[0]    
    add_asset = JSONSchemaField(schema = type_json_schema, options = options)

Instead of passing id=1 I want to pass the value I got in self.request

I referred this link Django app generating forms dynamically from JSON?

Thanks in advance


Solution

  • I found out the answer for my issue Here is the code that I made changes in formclass

    def assetAddJsonView(request,pk):
        def __init__(self, *args, **kwargs):
            ids = kwargs.pop('id')
            super(AssetAddjsonForm, self).__init__(*args, **kwargs)
            type_json_schema = Types.objects.values_list('details').get(id=ids)
            self.fields['add_asset'] = JSONSchemaField(schema=list(type_json_schema)[0], options = options)