Answer the question
In order to leave comments, you need to log in
How to implement form creation functionality in Django?
I need to create forms in the following order:
1. Create a name for the form (generator)
2. Create the steps for filling out the form
3. And add fields to these steps To then use these forms to fill out on the site.
How can this functionality be implemented?
from django.db import models
from enum import Enum
class Generator(models.Model):
name = models.CharField(max_length=255, verbose_name='Название')
url = models.URLField(verbose_name='Сссылка для запросов')
cost = models.DecimalField(max_digits=7, decimal_places=2, null=True)
def __str__(self):
return self.name
class Step(models.Model):
generator = models.ForeignKey(Generator, on_delete=models.CASCADE, related_name='steps', verbose_name='Генератор')
name = models.CharField(max_length=255, verbose_name='Название')
def __str__(self):
return f'{self.generator} - {self.name}'
class FieldChoices(Enum):
text = 'text'
email = 'email'
tel = 'tel'
url = 'url'
password = 'password'
number = 'number'
search = 'search'
date = 'date'
time = 'time'
range = 'range'
radio = 'radio'
checkbox = 'checkbox'
color = 'color'
file = 'file'
hidden = 'hidden'
class Field(models.Model):
step = models.ForeignKey(Step, on_delete=models.CASCADE, related_name='fields', verbose_name='Шаг')
name = models.CharField(max_length=255, verbose_name='Название')
type = models.CharField(max_length=255, choices=((choice.name, choice.value) for choice in FieldChoices))
def __str__(self):
return f'{self.step} - {self.name} {self.type}'
Answer the question
In order to leave comments, you need to log in
I came to the following output:
If you are talking about dynamic creation of forms, then in python you can create classes using metaclasses. Well written here https://proglib.io/p/metaclasses-in-python/
Further here at the end https://www.b-list.org/weblog/2008/nov/09/dynamic-... there is an example how to create a form dynamically
This way you can create forms dynamically
Aman use PostgreSQL and JSONField, you can store fields and all the necessary information to generate the field there. The field class can be retrieved from a string ('CharField', 'IntegerField'... etc.) using getattr and the django.db.models module. field = field_class(**field_kwargs). Something like this.
And to create forms, you can use formtools , a very useful thing, you can put forms and formsets there.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question