I have a django template with an update form, for an invoices application.
I want to allow to update the record after it was saved.
One of the model fields is manager which is a foreign key:
class Invoice(models.Model):
manager = models.ForeignKey(User, on_delete=models.CASCADE,null=True ,blank=True)
The problem is that I don't to display the manager's user id, but his/her first name, so I want to populate the select tag with all manager's first name. I have tried this:
<select id="id_manager" name="manager">
{% for manager in managers %}
{{ manager }} || {{ initial_manager }}
{% if manager == initial_manager %}
<option value="{{ manager.user.id }}" selected>{{ manager.user.first_name }}</option>
{% else %}
<option value="{{ manager.user.id }}">{{ manager.user.first_name }}</option>
{% endif %}
{% endfor %}
</select>
This is the views.py part:
managers = Profile.objects.filter(Q(role = 'manager') | Q(role = 'cfo') | Q(role = 'ceo') | Q(role = 'sec'))
projects = Project.objects.all()
form = InvoiceForm(instance = invoice)
initial_manager = invoice.manager
return render(request, "invoice/update.html", {'form': form, 'managers':managers, 'projects':projects, 'initial_manager':initial_manager})
I have added this to see the values of the variables:
{{ manager }} || {{ initial_manager }}
and I see for example " 102 || 102 ", which means that they are equal but the if part doesn't run, it always goes to the else part. It doesn't matter what I've tried, I have tried passing initial_manager as a string, comparing manager to " 102 " or to "102" or 102, but nothing works.
Can someone help me?
CodePudding user response:
if both are the same value but it's returning false when using if then try modify the code to make them both float using floatformat for your case
{% if manager|floatformat:"0" == initial_manager|floatformat:"0" %}
<option value="{{ manager.user.id }}" selected>{{ manager.user.first_name }}</option>
{% else %}
<option value="{{ manager.user.id }}">{{ manager.user.first_name }}</option>
{% endif %}
this will make them both float with 0 decimal so it's like converting them into an integer. see this also
CodePudding user response:
Thanks for the help. I've used stringformat instead of floatformat.
<select id="id_manager" name="manager">
{% for manager in managers %}
{{ manager }} || {{ initial_manager }}
{% if manager|stringformat:'s' == initial_manager|stringformat:'s' %}
<option value="{{ manager.user.id }}" selected>{{ manager.user.first_name }}</option>
{% else %}
<option value="{{ manager.user.id }}">{{ manager.user.first_name }}</option>
{% endif %}
{% endfor %}
</select>
Now it works. I appreciate your help