context data remain - unusual behavior?

Hello, everyone,
I’m just wondering about a behavior in my app.
I hope the code snippets are sufficient.

When the code goes into the second IF query, the context is extended with “error_message” and the template “app/location-query.html” is rendered - correct. Now the error message (in the frontend) is displayed in this template - correct. If I now go further and pass the IF query, the template “app/map.html” is rendered - also correctly. But now the “error_message” is displayed in the map.html - I don’t understand this. Why is the key still in the context variable?

I solved the problem by doing:

    def post(self, request):
        context = self.context
        context["error_message"] = ""

added - but would like to understand why it is the way it is.

class LocationView(View):
    location_type = LocationTypeData.objects.all()
    location_regulations = LocationRegulationsData.objects.all()
    context = {

    def get(self, request):
        return render(request, "app/location-query.html",)
    def post(self, request):
        for request_data in request.POST:
            if request_data == "button_location_query":
                if request.POST["location_query"] == "":
                    context = self.context
                    context["error_message"] = "You must provide your location!"
                    return render(request, "app/location-query.html", context)

                lat, lng = GetLatLngFromAdress(request.POST["location_query"])
                context = self.context
                context["location_query_lat"] = lat
                context["location_query_lng"] = lng
                return render(request, "app/map.html", context)


{% if error_message %}
      <div class="mlrt20 error_message">
          <p>{{ error_message }}</p>
{% endif %}

You must be getting multiple posts being submitted. Assuming this is an accurate copy of your code, it’s not possible for one view to return two separate responses from a single request.

So even if it works, isn’t it a good solution?

Should I then in a view - never render different templates?

I think this has to do with class vs instance variables in python. It looks like you’re modifying the class variable on the View class itself so it remains changed between requests. Instead of referencing it as self.context, create a new dictionary each time. If you want to re-use context, try creating a method called “get_context_data”, and call that method to get your context. I suggest this name specifically so it can be similar to the method that exists on generic views

1 Like