0

I've been looking all over stack and I just can't get anything to work.

The simpler for of my doubt is, I have a context variable, which I have to reassign inside a for loop, and I can, but when a new iteration begins, the variable is reset to it's original context value. So my question is, how do I keep the assigned value persistent throughout the loop?

I am assigning the value like this:

{% with task.new_stage as current %}{% endwith %}

The full excerpt of the code follows:

{% for task in tasks_list %}
<h3>At Beg {{current}}</h3>
{% if task.project_stage.id != current %}
<div id="tasks-container-{{ task.project_stage.id }}" class="task-container btn-group-vertical col-md-3">
{% endif %}
    <div class="panel my-panel tasks-panel col-md-11 {% if task.project_stage.has_started and not task.project_stage.has_ended %}active{% endif %} ">
        <span class="text-uppercase">{{ task.task_name }}</span>
        <div class="col-md-12">
            <img id="task-{{ task.id }}" class="download-pdf" src="{% static 'dpp/images/cloud.png' %}" />
        </div>
    </div>
{% if task.project_stage.id != current %}
</div>{% with task.new_stage as current %}<h3>At End{{current}}</h3>{% endwith %}
{% endif %}
{% endfor %}

View:

def get(self, request):
    if not request.user.is_authenticated():
        form = self.form_class(None)
        return render(request, 'dpp/login.html', {'form': form})

    tasks_list = ProjectTask.objects.all()
    context = {
        'tasks_list' : tasks_list,
        'current' : 0,
    }
    return render(request, self.template_name, context)
0

1 Answer 1

2

The context of {% with %} lasts until {% endwith %}. You end the block immediately after starting it, so it literally has no effect.

You shouldn't be trying to reassign variables inside the context. If you just want to check if something has changed since the last iteration, you should use the template tag specifically designed for that: ifchanged.

Sign up to request clarification or add additional context in comments.

1 Comment

So, now I now a little bit more about Django and it's withs :P Thanks a million!! I have now been able to do what I wanted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.