Generate a modelform in django

Django -- Posted on Oct. 15, 2024

Generate a modelform in django

              
                from django import forms
from django.forms import ModelForm

def create_modelform(model_class, include_fields=None, exclude_fields=None):
    """
    Dynamically create a ModelForm based on the model class passed as an argument.
    You can specify fields to include or exclude.
    :param model_class: The model class to base the form on.
    :param include_fields: A list of fields to include in the form (default: all fields).
    :param exclude_fields: A list of fields to exclude from the form (default: None).
    """
    class DynamicModelForm(ModelForm):
        class Meta:
            model = model_class
            # If specific fields are provided, use them; otherwise, include all fields
            if include_fields is not None:
                fields = include_fields
            elif exclude_fields is not None:
                exclude = exclude_fields
            else:
                fields = '__all__'  # Include all fields by default

    return DynamicModelForm
                  
   
            

Related Posts