Home > OS >  Select radio item in edit view Django Template
Select radio item in edit view Django Template

Time:04-16

I am making an edit view and I would like to have some radio fields selected when fetching the results. My issue is that I can't make my values of the forloop and the values from database comparing correctly. Let me be more clear with some code. I have these lists named mission_entry and gradings. mission_entry has some grades inside it, a vote from 1 to 5 in each value of the list.

views.py

    mission_entry = MissionEntry.objects.filter(log_entry_id=log_entry_id)
    gradings = range(1,6)

models.py

 GRADING_VALUE = (
    ('1', '1'),
    ('2', '2'),
    ('3', '3'),
    ('4', '4'),
    ('5', '5'),
)
    class MissionEntry(models.Model):
        student = models.ForeignKey(
            Student, on_delete=models.DO_NOTHING, blank=True, null=True)
        mission = models.ForeignKey(
            Mission, on_delete=models.DO_NOTHING, null=True, blank=True)
        log_entry = models.ForeignKey(
            LogEntry, on_delete=models.CASCADE, blank=True, null=True)
        learning_objective = models.ForeignKey(
            LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True)
        grade = models.CharField(
            max_length=10, choices=GRADING_VALUE, blank=True, null=True)
        comment = models.TextField(null=True, blank=True)
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)

template

 {% for lo in mission_entry %}
      <tr>
        <td id='learning_obj'>{{lo.learning_objective.name}}</td>
        {% for grade in gradings %}
          <td>
            <input  {% if lo.grade == grade %}selected{% endif %} type="radio" value="{{grade}}" name="grade{{lo.learning_objective.name}}" id="grade" required/>
          </td>
        {% endfor %}
        <td><input type="text"  name="note" id='note' value="{{lo.comment}}"></td>
      </tr> 
      {% endfor %}

I know that {% if lo.grade == grade %}selected{% endif %} is the wrong piece of code. Basically I am comparing in the template a string with an integer, but I can't understand how to manipulate my variables to compare them. Any suggestion?

CodePudding user response:

As you note, you're comparing strings to integers, which is why it doesn't work. You could change gradings to be strings instead of integers:

gradings = list(map(str, range(1, 6)))

Note, also, that both map and range return a generator - which means you'll only be able to iterate over it once in your template. To fix this, you need to first convert it to a list.

Where map converts every item in the iterable to a string.

Alternatively, you could change your grade field to an IntegerField instead of a CharField. This would be more appropriate if you only intend to store integer values, and would be better suited to things like ordering items by grade in future.

  • Related