0

I am passing a queryset of objects to a template. How can I pass that queryset back to the view when a form is submitted?

This is what I have:

{% for engine in engines %}
{{engine.manufacturer}}: {{engine.name}}
{% endfor %}
...
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="hidden" name="engine_ids" value="{{engines}}"/>
<input type="submit" value="Export engines" name="export"/>
</form>

Normally request.POST.getlist('engine_ids') would return the string

[<Engine: Engine Object>, <Engine: Engine Object>, <Engine: Engine Object>, <Engine: Engine Object>, ... '...(remaining elements truncated)...']

Which is not helpful, so I did a dirty cheap hack and changed the models __unicode__ function to return the id.

Now I get:

[<Engine: 2>, <Engine: 4>, <Engine: 7>, <Engine: 9>, ... '...(remaining elements truncated)...']

which is more useful because I can now generate a queryset from those IDs. However using this method, I am limited to 20 elements; anything after 20 shows as '...(remaining elements truncated)...'.

My question is, what are alternative ways of doing this? It would be great if I could do something like

{% for engine in engines %}
{{engine.manufacturer}}: {{engine.name}}
**add engine.id to a list called engine_id_list**
{% endfor %}
...
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="hidden" name="engine_ids" value=**engine_id_list**/>
<input type="submit" value="Export engines" name="export"/>
</form>

2 Answers 2

1

Ah, I figured it out;

<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="hidden" name="engine_ids" value="{% for engine in engines %}{{engine.id}},{% endfor %}"/>
<input type="submit" value="Export engines" name="export"/>
</form>
Sign up to request clarification or add additional context in comments.

Comments

0
import json
...
return render(request, 'template', {'engine_id_list': json.dumps([e.id for e in Engine.objects.filter(thefilter)])}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.