[Answer]-Django dynamic page generation with templates

1👍

I agree with the comments above, using forms is almost always a better idea. But in response to your problem, if you are not passing the bar variable to the template, the loop that parses the checkboxes will not be executed. You would need to add bar to the context for extend.html:

return render(request,'extend/extend.html',
    {'result':result,'p':queried_values, 'bar':strings_from_database})

Are you not doing this just to prevent hitting the DB twice? Has it proven a very expensive query to run?

Apart from setting up caching, you can always pass ALL the checkboxes “names” along with the form. You can add hidden inputs, like so:

{% for foo in bar %}
    <input type="checkbox" name="foovar" value="{{foo.name}}" {%if foo.name in p %}checked="checked"{%endif%}>{{foo.name}}<br>
    <input type="hidden" name="foovar_all" value="{{foo.name}}" />
{%endfor%}

Then you need to collect the values with something like:

bar = request.POST.getlist('foovar_all')

But you would need to rethink your code so the bar variables hold just the names of those objects in both views, it looks like it is a list of objects currently. Again, is it really necessary to avoid that query?

👤AJJ

Leave a comment