Прежде всего, я приглашаю вас перейти с FBV на CBV, поверьте мне, это положительно изменит все программирование в Django.
Я не вижу ваш пост-метод. Я оставлю вас здесь, как я это сделал:
[template.html]
<form action="" method="POST"> {% csrf_token %}
{% for test in tests %}
{% for subtest in subtests %}
<input type="hidden" name="test_id" value="{{test.id}}">
{% if test.id == subtest.test_id && subtest.selected %}
<label>
<input type="checkbox" name="{{subtest.id}}" checked>{{subtest.name}}
</label>
{% else %}
<label>
<input type="checkbox" name="{{subtest.id}}">{{subtest.name}}
</label>
{% endif %}
{% endfor %}
{% endfor %}
...
<input class="btn btn-success" type="submit" value="GENERATE REPORT">
</form>
[views.py]
from .models import (
Subtest,
Test,
)
from django.views.generic import ListView
class ListSubsets(ListView):
context_object_name = 'tests' # This replace context['tests']
model = Test
paginate_by = 1
template_name = 'core/index.html'
def get_context_data(self, **kwargs):
context = super(ListSubsets, self).get_context_data(**kwargs)
context['subtests'] = Subtest.objects.all()
# context['tests'] = Test.objects.all() # Without prefetch_related
return context
def post(self, request):
post_dict = request.POST.dict()
# test = Test.objects.get(id = post_dict['test_id'])
subtests = Subtest.objects.all()
for subtest in subtests:
try:
if str(subtest.test_id) in post_dict:
update = Subtest.objects.get(test = subtest.test_id)
update.selected = True
update.save()
except:
print("Doesn't exist.")
return self.get(request, *args, **kwargs)
Есть более тонкие способы сделать это, другие более эффективные способы, но действительно правильная вещь должна быть JavaScript. Проверьте угол, я приглашаю вас, и, пожалуйста, переключитесь на CBV.
------------------------------- - o --------------------------------
[settings.py]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates/')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
# Our context processor for every app.
# Core.
'apps.functions.processor.cntxt_prcssr_templates_core',
],
},
},
]
[processor.py]
from .models import (
Test,
Subtest
)
# tests = Test.objects.all()
# subtests = Subtest.objects.all()
def cntxt_prcssr_templates_core(request=None):
# TEST.
'tests': Test.objects.all(),
# 'tests': tests,
# SUBTEST
'subtests': Subtest.objects.all(),
# 'subtests': subtests,
return cntxt_templates_core
Тогда вы получаете доступ только к тестам или подтестам из любого шаблона. (html)