1

I have a database with multiple user names and phone numbers attached to each user. On the Django template that I created the user is presented with a list of names, and the user can click on a name, or multiple names, and the database is to respond with the phone number assigned to the name. However, I am using a for loop within the Django template to iterate over the names in the database to display for the user, as the count can change. It works correctly when I select one name, however, if I select multiple name, it takes the last name selected versus displaying all names. This error is due to my for loop solution which has the same "name" assigned to all inputs. Anyone have an idea on how I can approach this?

My View form:

def select_contact(request):
    alldata = identity_log.objects.values_list("first_name", flat=True)
    #https://docs.djangoproject.com/en/4.0/ref/models/querysets/
    checkform = contact_form(request.POST or None)
    context = {'alldata': alldata}
    print(checkform)
    display_type = request.POST.get("contact_option", None)
    if display_type in alldata:
        print(display_type)
    return render(request, 'message_me/select_contact.html', context)

My template:

{% extends "base.html" %}
{% load static %}


{% block body %}
<p>Please select your favorite Web language:</p>
{% for x in alldata %}
  <form id="contact_option" role="form" action="" method="POST">
    {% csrf_token %}
    <input type="checkbox" id="contact_option" name="contact_option" value="{{x}}">
  <label for="contact_option">{{x}}</label><br>
{% endfor %}
    <div class="row">
        <div class="col-md-12"> <input type="submit" name="submit" class="btn btn-success btn-send pt-2 btn-block " value="Continue"> </div>
    </div>
</form>

{% endblock %}

image of the HTML doc

Sean
  • 21
  • 6

1 Answers1

0

Replace :

 <input type="checkbox" id="contact_option" name="contact_option" value="{{x}}">

with

 <input type="checkbox" id="contact_option{{x}}" name="contact_option{{x}}" value="{{x}}">

Now you have a unique id for each user.

Gaëtan GR
  • 1,380
  • 1
  • 5
  • 21
  • Gaëtan GR How do I call it on the view? My view does not have the {{x}} for loop. – Sean Dec 17 '21 at 13:38
  • You have a for loop in your template, I just used your code and added a unique name and id – Gaëtan GR Dec 17 '21 at 13:41
  • what do I put in place of "contact_option" in the view? display_type = request.POST.get("contact_option", None) – Sean Dec 17 '21 at 13:42
  • I used the following, but doesn't seem to work. I am testing by printing the output to the console display_type = request.POST.getlist("contact_option", None) Any thoughts @Gaëtan GR? – Sean Dec 17 '21 at 14:11