[Answered ]-Use variable as form fields in Django form template

1👍

You don’t need to use filters / template tags, etc. for this purpose. The simplest solution would be to loop over the form fields to render them:

<form>
{% for field in form %}
    {{ field|as_crispy_field }}
{%endfor%}
</form>

This will loop over all the fields in your form.

If you particularly care about the order of these fields you can call the forms order_fields method:

class Someform(forms.form):
    def __init__(self, artifact_obj, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for count, artifact in enumerate(artifact_obj):
            self.fields[f'artifact_{count}'] = forms.CharField(widget=forms.NumberInput())
        self.order_fields(["field_1", "field_2", ...] + [f"artifact_{i}" for i, _ in enumerate(artifact_obj)] + [..., "field_n"])

If you particularly want to render the other fields separately you can add a method to your form that will allow you to loop over these fields:

class Someform(forms.form):
    def __init__(self, artifact_obj, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for count, artifact in enumerate(artifact_obj):
            self.fields[f'artifact_{count}'] = forms.CharField(widget=forms.NumberInput())
        self.artifact_length = len(artifact_obj)
    
    def artifact_fields(self):
        return [self[f'artifact_{i}'] for i in range(self.artifact_length)]

And then loop over these in the template:

<form>
{% for field in form.artifact_fields %}
    {{ field|as_crispy_field }}
{%endfor%}
</form>

Leave a comment