简体   繁体   中英

Django dynamic page generation with templates

I want to generate a page using templates and content blocks. The homepage generates a bunch of checkboxes to generate a searchquery for some specific values.

<div id="searchbar">
  {% for foo in bar %}
    <input type="checkbox" name="foovar" value={{foo.name}}{%if foo.name in p %}checked=checked{%endif%}>{{foo.name}}<br>
  {%endfor%}
  <input type="submit" value="Submit">
</div>
<div id="searchresult">
{% block content %}
{% endblock %}

The value 'bar' is the parameter passed to the template containing all specific values:

 return render_to_response('testlink/foobar.html',{'bar':strings_from_database})

Now, upon submitting the values, they are passed to my view, some magic happens, and the result is passed via

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

result is the result, p contains the queried values (to keep the checkboxes checked after submitting).

 {% extends "testlink/foobar.html" %}
 {% block content %}
 <b>results:</b>  <br>
 {% for result in result %}
     {{result.someattribute}}<br>
 {% endfor %}
 {% endblock %}

Now, my problem: The checkboxes disappear, probably as the 'for foo in bar' loop is executed again. Is there a way to prevent that from happening, without to hardcode the checkboxes into my template? This would work (i did it with a few checkboxes, but doing this with too many searchvalues is no fun. Also i would like to avoid additional database hits and passing the parameters again.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM