About Reordering Dictionary Keys and Values

You can reorder the keys of a dictionary using this dictionary comprehension:

import json

with open("data.json", "r") as file:
    data = json.load(file)

new_order = ["title", "slug", "status"]
data = {key: data[key] for key in new_order if key in data}

That can be used practically to reorder the form fields like so:

from django import forms
from .models import Post, Category

class PostForm(forms.ModelForm)
    categories = forms.ModelMultipleChoiceField(
        queryset=Category.objects.all(),
        required=False
    )

    class Meta:
        model = Post
        fields = ["title", "slug", "status"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        field_order = [
            "title",
            "slug",
            "categories",
            "status",
        ]
        self.fields = {
            key: self.fields[key] 
            for key in field_order 
            if key in self.fields
        }

Tips and Tricks Programming Django 5.2 Django 4.2 Django 3.2 Python 3