Junior — Middle
How can you implement automatic generation and display of forms from a data model, similar to the Form component in Django?
sobes.tech AI
Answer from AI
To automatically generate and display forms from a data model, as in Django, you can use an approach where the form is built dynamically based on the model description (for example, fields and their types). In Python, this can be implemented using metaclasses, descriptors, or libraries that analyze the model and create the form.
A simplified example:
class Field:
def __init__(self, field_type, label):
self.field_type = field_type
self.label = label
class ModelMeta(type):
def __new__(cls, name, bases, attrs):
fields = {k: v for k, v in attrs.items() if isinstance(v, Field)}
attrs['_fields'] = fields
return super().__new__(cls, name, bases, attrs)
class Model(metaclass=ModelMeta):
pass
class User(Model):
name = Field(str, 'Name')
age = Field(int, 'Age')
class Form:
def __init__(self, model_cls):
self.fields = model_cls._fields
def render(self):
for name, field in self.fields.items():
print(f"<label>{field.label}</label><input type='{field.field_type.__name__}' name='{name}' />")
form = Form(User)
form.render()
This code outputs HTML-like form elements based on the fields of the User model. In real projects, frameworks (Django, WTForms, Pydantic) or libraries for validation and form rendering are used.