Search code examples
pythonhtmldjangodjango-viewsdjango-templates

How to use variable to iterate in django template?


I'm using python and django and I would like to use a variable I entered in a previous input, to iterate over creating multiple other input fields.

This is the part in the Django template where I ask the number I would like to use in the iteration:

<form method="GET">
    <label for="grondstoffen_count" style="font-family: Oswald, sans-serif;">Give how many products were delivered:</label>
    <input type="number" name="grondstoffen_count" id="grondstoffen_count" min="0" required>
    <button type="submit" name="submit_count">Bevestig</button>
</form>

This is my views.py, in my last elif I generate a string of the sequence up to the input number. When I have the string I return it to the Django template:

class BehandelNieuweVoorraadView(generic.ListView):
    template_name = "Ano_app/BehandelNieuweVoorraad.html"
    model = Grondstof
    checkaankomst = []

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['grondstof_options'] = self.optieLijst(1)

        if self.checkaankomst == []:    
            context['aankomstgrondstoffen'] = self.optieLijst(2)
            self.checkaankomst.extend(context['aankomstgrondstoffen'])
        else:
            context['aankomstgrondstoffen'] = self.checkaankomst

        return context

    def optieLijst(self, a):
        grondstof_options = Grondstof.objects.distinct().values_list('naam', flat=True)
        if a == 1:
            return sorted(grondstof_options)
        else:
            aankomstgrondstoffen = random.sample(list(grondstof_options), random.randint(2, 5))
            return sorted(aankomstgrondstoffen)

    def get_queryset(self):
        if 'submit_hoeveelheden' in self.request.GET:
            grondstofnamen = []
            for i in range(1, 6):
                grondstofnaam = self.request.GET.get(f"query_grondstof{i}naam", False)
                grondstofnamen.append(grondstofnaam)

            grondstofhoeveelheden = []
            for i in range(1, 6):
                grondstofhoeveelheid = self.request.GET.get(f"query_grondstof{i}hoeveelheid", False)
                if grondstofhoeveelheid == '':
                    grondstofhoeveelheden.append(0.0)
                else:
                    grondstofhoeveelheden.append(float(grondstofhoeveelheid))

            nietOpgeslagen = verdeelAangekomenGrondstoffen(grondstofnamen, grondstofhoeveelheden, Opslagplaats.objects.all(), Grondstof.objects.all(), Eindproduct.objects.all())

        elif 'submit_correctelevering' in self.request.GET:
            print("naar orderpagina")
        elif 'submit_count' in self.request.GET:
            grondstoffen_count = int(self.request.GET.get('grondstoffen_count', 0))

            volgordelijst = ""
            for i in range(1, grondstoffen_count + 1):
                volgordelijst += str(i)

            return render(self.request, 'Ano_app/BehandelNieuweVoorraad.html', {'volgordelijst': volgordelijst})

In the template I receive the 'volgordelijst' and I would like to use that variable for the loop. I would like to have as many input fields as the number in the original input but when I run the server it doesn't show a single one. When I change 'volgordelijst' by "12345" it works perfectly. I also have other lists I give to the template and there I have no problem whatsoever to iterate:

        <form method='GET'>
            {% for i in volgordelijst %}
                {% with key="query_grondstof"|add:i|add:"hoeveelheid" %}
                <div style="display: inline-block; margin-right: 10px;">
                    <h4 style="font-family: Oswald, sans-serif;">Grondstof {{ i }} naam:</h4>
                    <input list="grondstof{{ i }}datalist" name="query_grondstof{{ i }}naam" id="grondstof{{ i }}" required>
                    <datalist id="grondstof{{ i }}datalist">
                        {% for option in grondstof_options %}
                            <option value="{{ option }}">
                        {% endfor %}
                    </datalist>
                </div>
                <div style="display: inline-block; margin-right: 10px;">
                    <h4 style="font-family: Oswald, sans-serif;">Grondstof {{ i }} hoeveelheid in ton:</h4>
                    <input type='number' step="0.01" name='{{ key }}' value='{{ request.GET.key }}' min="0" required>
                </div>
                <br>
                {% endwith %}
            {% endfor %}
        </form>

Solution

  • Now that you have posted your view I can see the problem. You are tryig to pass the volgordelijst variable to the template from the get_queryset function. The get_queryset function is supposed to return a queryset to the get_context_data function. To pass a variable to the template you need to pass it from the get_context_data function.