Search code examples
pythondjangodjango-viewsdjango-templatesdjango-datatable

Retrieving data from Django HTML form and passing it to a MySQL database


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


Solution

  • 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.