Home > Net >  How can I set an attribute to use in both POST and GET methods in django class-based views?
How can I set an attribute to use in both POST and GET methods in django class-based views?

Time:07-09

So I'm building a class-based view that uses data from a table on my db, both on POST and GET methods. I've been trying to set an attribute with the table to mitigate the time that it would take to pull the table again for the sake of performance.

Because of how functions/methods work I can't set an attribute like this:

class MyClass (View):

    @md(login_required(login_url='login',redirect_field_name=None))
    def get(self, request):
        con = create_engine('mysql mysqlconnector://user:password@localhost:8000/schema')
        
        #function to get a dict with db tables
        tabs  =  get_tables(con)
        
        #Trying to make the attribute
        self.table = tabs['table_That_I_need']
        
        context{'data':tabs}
        return render(request, 'markowitz/markowitz.html',context)

    @md(login_required(login_url='login',redirect_field_name=None))
    def post(self, request):
        
        #this gives me an error since the attribute was not set
        table = self.table

        form = MarkowitzForm(request.POST,table)
         
        if form.is_valid():
           pass

        return render(request, 'markowitz/results.html')

I've been trying to use setattr but it doesn't seem to be working

CodePudding user response:

With self.table = ... you are essentially setting the attribute on the current instance. And Django creates new instances for each request. Which means, the table attribute of one instance isn't shared with another instance.

What yo want to do is set the attribute on the MyClass itself:

def get(...):
    ...
    if not hasattr(self.__class__, 'table'):
        # set table attr if not already present
        setattr(self.__class__, 'table', tabs['table_That_I_need'])
    ...
  • Related