Reputation: 3966
I have a form which represents a list of selected products, where each product is chosen from a select box. The select box chooses the PK of the product, but shows the PK + the Name of the product, something like: E12 - Valve
or E58 - Rotary nozzle
. Now, my specific situation is that I have a predefined set of products chosen for the user and the user cannot deviate from this selection of products. Thus, the user cannot be able to change the selected product. Further, this product form is an inlineformset_factory
, not the main form.
I display my product form like this:
<table class="field_container" id="prodTable">
<tr><th></th><th>CID</th><th>Qty</th></tr>
{{ pform.management_form}}
{% for form in pform %}
<tr class="pform_set">
{% for field in form %}
<td class="product-item">{{ field }} {% if field.errors %} {{ field.errors }} {% endif %} </td>
{% endfor %}
</tr>
{% endfor %}
</table>
If I change {{ field }}
to {{ field.value }}
then all I get is E12
which is the PK of the foreign model. However, I need it to show E12 -- Valve
. Is there any way to do this?
Upvotes: 0
Views: 85
Reputation: 13328
Sounds like a custom template tag might work. Something like -
from your_module import Product
def get_product_string(value):
try:
product = Product.objects.get(pk=value);
return value + " -- " + product.name
except DoesNotExist:
return value
Then alter your template so instead of {{ field.value }}
you do can do {{ field.value|get_product_string }}
Upvotes: 1