'How to get the data associated with a checkbox in Django views

I have a database that I'm trying to access via a template in Django. I'd like to be able to select some checkboxes and have it return the items associated with those checkboxes in my views.py so I can perform some logic on that data.

template.py

<input type="checkbox" checked autocomplete="off" name="tag" value={{ recipe.id }} />{{ recipe }}

views.py

def create_list(request):
    check_values = request.POST.getlist('tag')
    context = {'check_values': check_values)
    return render(request, 'grocery_lists/create_list.html', context)

The create_list.html page simply displays {{ check_values }}. This was my attempt at a troubleshooting step so I could see what was stored in the variable check_values, However, check_values ends up being an empty list. I'm having trouble finding a solution that fits my use case. Thank you in advance.



Solution 1:[1]

Based on your comment - the checkbox value isn't making it to your view because it is not in a form. Wrap it in a form with method="POST" and action="{% url 'create_list' %}" and have a submit button submit that form - and then you should see it. Something like this:

<form method="POST" action="{% url 'create_list' %}">
    <input type="checkbox" checked autocomplete="off" name="tag" value={{ recipe.id }} />{{ recipe }}
    <button type="submit">Submit</button>
</form>

I'd also add that forms in Django are probably worth checking out https://docs.djangoproject.com/en/4.0/topics/forms/

Django can handle rendering forms for you automatically based on models.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pzutils