Django View class keeps values

Asked

Viewed 125 times

2

A curiosity that has accompanied me for a long time in Django and I never managed to heal:

Next. Let’s say I have something like:

from django.shortcuts import render
from django.views import View

from pagina.models import Config

class BasicView(View):
  try:
    dados = {
      'email': Config.objects.get(variavel = 'email').valor,
    }
  except:
    dados = {}

class TelaView(BasicView):
  def get(self, request, **kwargs):
    self.template_name = 'base.html'
    return render(request, self.template_name, self.dados)

Then, in the base.html template, I would call {{email}} and Django would show the registration in the database.

Now, if I were to keep the server running and modify the email log in the database so that the new email appears in the template, it would be necessary to stop the server and run it again.

My question: Why this happens and how to get around this?

  • No one’s ever been through this before?

1 answer

2


This is because when python will run a script it creates a kind of cache of the files involved (those files tralala.pyc or else the files that are inside the directory __pycache__). Therefore, it performs the import of information between files only once (when it runs), not every time the view is called.

This is a standard behavior of the language itself, if you need to provide this information dynamically (it will be changed from time to time), look for a way to store it in the database through an object and use some queryset to search for it.

Should it help, here has the documentation on querysets and here documentation on databases. In case I haven’t been completely clear, I hope I’ve at least helped.

  • Boy... your answer was very pertinent. I imagined something like that anyway. But let’s say I have, in addition to Telaview, another 4 views and, in all, I have to load the 'email' variable of the example. Do you know any way I can do this without having to repeat the self line.data['email'] = Config.objects.get(variable = 'email'). value for each view? How do you do this in your projects?

  • Search python and Environment variables (Python and environment variables).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.