Reputation: 2185
I'm trying to create a selection box in a HTML table where the given name should be selected in the combo box. In order to do this, I need to create a nested loop. The outer loop creates the rows, whereas the inner loop fills the grid cell with options for "Resources". For this example I'm only showing the code creating the Resource cell.
The nested loop creates the items, and contains an if statement comparing the action.owner value with the resource.name value. If the items match, the option value should be selected. The server runs with the code, and I cannot find any hidden problems. However I'm not getting the expected results. No item is being selected. Any idea what I'm doing wrong?
Note that I have only started learning Django and web development a week ago!
{% for action in actions %}
<tr>
<td>
<SELECT class="custom-select">
{% for resource in resources %}
<option value = "{{resource.name}}" {% if action.owner == resource.name %}selected="selected"{% endif %}>{{resource.name}}</option>
{% endfor %}
</SELECT>
</td>
</tr>
{% endfor %}
Some HTML output for a random row that I selected with a dummy html tag to show which action.owner was in question:
<td> <SELECT class="custom-select"> <option value = "None" actionOwnerVal = John >None</option> <option value = John" actionOwnerVal = John >John</option> <option value = "Bob" actionOwnerVal = John >Bob</option> </SELECT> </td>
The Actions class:
actionChoices = (
('New','New'),
('In Progress','In Progress'),
('Critical','Critical'),
('Done','Done')
)
class Actions(models.Model):
project = models.ForeignKey(Projects, on_delete=models.CASCADE)
task = models.CharField(max_length=500)
owner = models.ForeignKey(Resources, on_delete=models.CASCADE,default = 0)
closureDate = models.DateTimeField(default = datetime.now,blank=True)
status = models.CharField(max_length=500,choices=actionChoices,default='New')
notes = models.CharField(max_length=1000)
def __str__(self):
return(self.task)
class Meta:
verbose_name_plural = "Actions"
The Resources class:
class Resources(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return(self.name)
class Meta:
verbose_name_plural = "Resources"
Upvotes: 1
Views: 878
Reputation: 33285
resource
and action.owner
are both Resource
objects, so you should be comparing resource.name
to action.owner.name
.
action.owner
appeared to be a string value when printed in the template, because its class defines a __str__
method.
Upvotes: 2