How to autoincrement values checkbox with jinja2 (Django) with reset

Question:

I need to autoincrement value in my checkbox and reset value when I generated new massive of checkbox

forloop.count dont reset
{% for ans in Answ %}

    {% if ans.question_id_id == Questions.id %}
        <input type="hidden" value="{{ Questions.id }}" name="id">
       <div class="form-check" ><label><input type="checkbox" value="{{ ans.id }}" name="answer"> {{ ans.answer }} </label></div>
    {% endif %}

{% endfor %}

views.py

class AnswerQuestionView (LoginRequiredMixin, DetailView):
login_url = '/login'
redirect_field_name = 'redirect_to'
model = Question
template_name = 'index.html'
context_object_name = 'Questions'
slug_field = 'pk'

def get_context_data(self, **kwargs):
    context = super(AnswerQuestionView, self).get_context_data(**kwargs)
    context['user_group'] = self.request.user.groups.values_list()[0][1]
    context['Answ'] = QuestAnswer.objects.all()

    return context
Asked By: LeonidPetrovich

||

Answers:

This is one of the many reasons why you should not do filtering in the template. Another very important one is performance: as the number of answers will grow, eventually the template rendering will take a lot of time.

You can filter in the view with:

class AnswerQuestionView(LoginRequiredMixin, DetailView):
    login_url = '/login'
    redirect_field_name = 'redirect_to'
    model = Question
    template_name = 'index.html'
    context_object_name = 'question'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['user_group'] = self.request.user.groups.values_list()[0][1]
        context['answers'] = QuestAnswer.objects.filter(question_id=self.object)
        return context

You probably can even use the related name:

class AnswerQuestionView(LoginRequiredMixin, DetailView):
    login_url = '/login'
    redirect_field_name = 'redirect_to'
    model = Question
    template_name = 'index.html'
    context_object_name = 'question'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['user_group'] = self.request.user.groups.values_list()[0][1]
        context['answers'] = self.object.questionanswer_set.all()
        return context

Note: Normally one does not add a suffix …_id to a ForeignKey field, since Django
will automatically add a "twin" field with an …_id suffix. Therefore it should
be question, instead of question_id.

Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.