0

I am using a JSONField to store a custom form with field labels/values. I am having an issue when rendering the form. Each time the form gets rendered, the order is changed since I am using a dictionary. I was thinking of adding an extra value to my JSONField just to store an integer, in which I can order by. I am wondering if this is a possible solution, or if there was any other "best" way to keep this form in order.

I have a simple model,

class House(models.Model):
    form = JSONField(default=dict)

Which in my view a json file is loaded into it with a json file as such.

{
    "outside": [
        {
            "fields": [
                {
                    "label": "Pool",
                    "value": ""
                },
                {
                    "label": "Shed",
                    "value": ""
                },
            ],
            "index": 0
        }
    ],

    "inside": [
        {
            "fields": [
                {
                    "label": "Bedrooms",
                    "value": ""
                },
                {
                    "label": "Baths",
                    "value": ""
                },
            ],
            "index": 1
        }
    ],

When the form is rendered in my view, I am using basic logic

house = House.objects.get(id=1)
form = house.form.items()
return render(request, template, context={'form': form}

The json loads fine the first time, with all fields with the label outside leading, and then fields with the label inside right after.

Outside
1.) Pool <input value="">
2.) Shed <input value="">

Inside
1.) Bedrooms <input value="">
2.) Baths <input value="">

Now running a hard page refresh, and printing out the house.form.items() the order is rearranged, and in doing so the template renders the form with inside fields leading, and outside fields following after. I definitely need to keep fields in order every time, so I added the index value, thinking it was a possibility to sort these items every time based off of the index value but really unsure of how to go about this?

master_j02
  • 377
  • 3
  • 13
  • Why not use lists instead of dictionaries if order matters? – Iain Shelvington Aug 25 '21 at 16:25
  • I do need to use key/value pairs since this is actually being rendered as a form the label(key) needs to have a value. the value(key) needs to have a value. I need them to have the association. – master_j02 Aug 25 '21 at 16:31

0 Answers0