Home > database >  Python DJango avoid assigning variables
Python DJango avoid assigning variables

Time:07-22

def myview(request):
    category=""
    brand=""
    series = ""
    model=""
    resolution=""
    ram=""

    #some process  
    
    return render(request ,'mypage.html',{'category':category,'brand':brand,'series':series
                                          'model':model,'resolution':resolution,'ram':ram} 

Sometimes in my Django projects I have to assign these variables first in my views because of the returning template tags. But doing this way is kinda ugly. Can I avoid assigning these variables in my views?

CodePudding user response:

You could define a dictionary that uses commonly used variables and re-use that in all of your views.

MY_VARS = {'category': '', 'brand': ''}

def myview(request):
    context = MY_VARS.copy()
    context.update({'more': ''})
    return render(request ,'mypage.html', context)

CodePudding user response:

I think having them listed out in your view is sensible so that you know what is being passed to your context, your code is far better like this even if you think it looks ugly. Depending on where your data comes from, your alternatives would be:

def myview(request):
   """ 
   Create a context variable and assign them all here to avoid creating 
   the dict in your render function
   """
   context = {'category':category,'brand':brand,'series':series, 
      'model':model,'resolution':resolution,'ram':ram} 

    #some process  
    
    return render(request ,'mypage.html', context)
def myview(request):
   """
   Use the ** unpacking method to easily unpack them into your context
   """
   context = {**my_variables, ...}

    #some process  

   return render(request, 'mypage.html', context)

The final option would be to generate these variables elsewhere, such as in a model manager or a metadata file and just call the class once in the view.

  • Related