Created
June 9, 2024 04:58
-
-
Save jefftriplett/3ca8bb4a4b97bdecec3a257ff5cd1cf9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import annotations | |
import inspect | |
import djclick as click | |
from django import forms | |
from django.core.management.base import CommandError | |
from django.utils.module_loading import import_string | |
from rich import print | |
[@click](https://micro.blog/click)() | |
@click.option("form_path", "--form-path", type=str, required=True) | |
def main(form_path): | |
try: | |
# Import the form using the dotted path | |
form_class = import_string(form_path) | |
except ImportError: | |
raise CommandError(f'Form "{form_path}" could not be imported') | |
# Ensure the imported class is a subclass of forms.ModelForm | |
if not inspect.isclass(form_class) or not issubclass(form_class, forms.ModelForm): | |
raise CommandError(f'[red]"{form_path}" is not a valid Django form[/red]') | |
form = form_class() | |
print('{% csrf_token %}\n') | |
for field in form: | |
print(f'<div class="form-group">') | |
print(f' {{% if form.{field.name}.is_hidden %}}') | |
print(f' {{{{ form.{field.name} }}}}') | |
print(f' {{% else %}}') | |
print(f' <div class="form-group">') | |
print(f' <label for="{{{{ form.{field.name}.id_for_label }}}}" class="block text-sm font-medium text-gray-700">') | |
print(f' {{{{ form.{field.name}.label }}}}') | |
print(f' </label>') | |
print(f' <div class="form-control">') | |
print(f' {{{{ form.{field.name} }}}}') | |
print(f' </div>') | |
print(f' {{% if form.{field.name}.help_text %}}') | |
print(f' <div class="mt-2 text-sm text-gray-500">') | |
print(f' {{{{ form.{field.name}.help_text }}}}') | |
print(f' </div>') | |
print(f' {{% endif %}}') | |
print(f' {{% for error in form.{field.name}.errors %}}') | |
print(f' <div class="mt-2 text-sm text-red-600">') | |
print(f' {{{{ error }}}}') | |
print(f' </div>') | |
print(f' {{% endfor %}}') | |
print(f' </div>') | |
print(f' {{% endif %}}') | |
print(f'</div>') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment