Home > Enterprise >  get checkbox values in django template and pass to view
get checkbox values in django template and pass to view

Time:08-03

I have a Group model:

class Group(models.Model):
   leader = models.ForeignKey(User, on_delete=models.CASCADE)
   name = models.CharField(max_length=55)
   description = models.TextField()
   joined = models.ManyToManyField(User, blank=True)

where I want the leader to have the ability to remove Users who have joined the Group. On the frontend, I have the list of members rendered:

{% if user.id == group.leader_id %}
  <form action="{% url 'remove_members' group.pk %}" method="POST">
    {% csrf_token %}
    <ul id='leaderList'>  
      {% for member in list %}
        <input type='checkbox'>{{ member }}</input>
      {% endfor %}
    </ul>
    <button type="submit">REMOVE</button>
</form>
{% endif %}

However, before I even write the view I need to be able to access the values of these checkboxes and pass the values over to my remove_members view. The view will be function based and will look something like this:

def remove_members(request, pk):
    group = Group.objects.get(id=request.POST.get('group_id'))
    #  I need a line here to access the checkbox values from the template so that I can run a for loop
    for member in checkbox_values:
        group.joined.remove(member)
    return HttpResponseRedirect(reverse('group_detail', args=[str(pk)]))

If I can retrieve the values of the checkboxes and pass them to this view on submit I think this should work to remove the members. Is there some simple thing I'm missing to passing the values?

CodePudding user response:

You need to set a name for the checkbox input that will be passed into request.POST:

<input type='checkbox' name='member' value="{{member.id}}">{{ member }}</input>

You then need to use getlist() to get the values for your for-loop:

members = request.POST.getlist('member')

This will give you their IDs, you then need to get the model objects from the DB.

  • Related