Hi all,
I am relatively new to Django, having been thrown into it for a project, but have decent knowledge of other web languages. I am trying to create a form that contains dynamic fields based upon values in a database, in this case, for example, each new row in a certain table is a new field in the form. This all works fine, until I need to submit it. I noticed my view wasn’t running, and when I inspected the form in the browser, my tag did not render at all, despite me placing it a few layers outside of where the dynamic content is rendered. Can anyone help here? I am confident my views.py and urls.py are set up correctly, as all my static forms work fine.
HTML Code:
{% load static %}
{% load modal_tags %}
{% load humanize %}
{% csrf_token %}
{% block content %}
<div class="add_row_wrapper">
<form method = "POST" action="{% url 'coreboard:add_row' %}">
<div class="row_form_wrapper">
{% csrf_token %}
<div id="text" class="show_form input_div">
{{ addRowForm.as_p }}
</div>
</div>
</form>
</div>
{% endblock %}
forms.py Code
class AddRowForm(forms.Form):
def __init__(self, *args, **kwargs):
super(AddRowForm, self).__init__(*args, **kwargs)
# Query the database to get data
data_from_db = Columns.objects.values() # Example query, you can customize this
# Process the data as needed
for item in data_from_db:
field_name = item["column_name"]
field_type = item["column_type"]
field_id = item["id"]
required = item["required"]
if field_type == 'Text':
field_class = forms.CharField
widget = forms.TextInput(attrs={"class": "form-control"})
elif field_type == 'Choice':
field_class = forms.ChoiceField
widget = forms.Choice(attrs={"class": "form-control"})
elif field_type == 'DateTime':
field_class = forms.DateTimeField
widget = forms.DateTimeInput(attrs={"class": "form-control"})
elif field_type == 'Person':
field_class = forms.CharField
widget = forms.TextInput(attrs={"class": "form-control"})
elif field_type == 'Number':
field_class = forms.DecimalField
widget = forms.NumberInput(attrs={"class": "form-control"})
elif field_type == 'YesNo':
field_class = forms.BooleanField
widget = forms.CheckboxInput(attrs={"class": "form-control"})
elif field_type == 'Image':
field_class = forms.CharField
widget = forms.TextInput(attrs={"class": "form-control"})
elif field_type == 'ProgressBar':
field_class = forms.IntegerField
widget = forms.NumberInput(attrs={"class": "form-control"})
if field_type == 'Number':
self.fields[f'field_{field_id}'] = field_class(
label=field_name,
required=required, # Adjust as needed
widget=widget,
help_text=item["description"],
max_value=item["max_value"],
min_value=item["min_value"]
)
else:
self.fields[f'field_{field_id}'] = field_class(
label=field_name,
required=required, # Adjust as needed
widget=widget,
help_text=item["description"]
)
Thanks!