Вопрос

I have a list in my template. For each item in the list, I have a {{ modelform }} that contains a checkbox. I can check the box and it updates as should. The problem is that when I check the box for one item and submit, it submits for all of the checkboxes because they are the same in each instance. Is there a way to set up a unique checkbox instance for each item in the list?

Current each modelform checkbox renders the same like this:

<input name="is_solution" type="checkbox" class="is_solution" id="is_solution">

I also tried using

test = request.POST.get('checkbox')

and

test = request.POST.get('checkbox')

thinking that using this I might be able to post an update in my view. I think I am going about this all wrong and I am lost. Essentially, I would like to have a checkbox on a list much like here on stackexchange where you can confirm an answer. Any suggestions?

Это было полезно?

Решение

You have to use form's prefix in the view like (just something unique for each form object):

def foo(request, ...):
    objs = Model.objects.filter(...)
    forms = []
    for i, obj in enumerate(objs):
        form = ModelForm(instance=obj, prefix=str(i))
        forms.append(form)
    ...

This will make sure each form has unique identifier, hence you will be able to submit a specific form.

And you can render the forms like usual in the template:

<form ...>
{% csrf_token %}
{% for form in forms %}
    {{ form }}
{% endfor %}
</form>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top