0
I have BaseContext view and other templateView. Token is created inside the template. I also checking the token cookie exists if not I redirect user to this url–> https://testdomain.com/get_token?origin=http://localhost:8000
class BaseContext(View):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
request = self.request
if request.COOKIES.get('token') is not None:
token = request.COOKIES.get('token')
bla bla bla
return context
else:
return HttpResponseRedirect('https://testdomain.com/get_token?origin=http://localhost:8000')
and I have another view which inherited from basecontext
class Services(BaseContext, TemplateView):
template_name = "services.html"
def get_context_data(self, **kwargs):
request = self.request
context = super().get_context_data(**kwargs)
context.update({'service_active': 'Active'})
return context
When I tried to load page, I got an error, like this, ‘HttpResponseRedirect’ object has no attribute 'update’
This could be because the super().get_context_data
function you’re calling has the possibility of not returning a dictionary. Try adding some kind of if
statement checking if the context variable is valid before trying to update it.
Hi, thanks for reply, I added is_valid context inside baseview and checked this context in my services view. It works for now. But I wonder is there any other good solution for this?
class BaseContext(View):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
request = self.request
if request.COOKIES.get('token') is not None:
token = request.COOKIES.get('token')
bla bla bla
context.update({'is_valid':False})
else:
context.update({'is_valid':False})
return context
class Services(BaseContext, TemplateView):
template_name = "services.html"
def get_context_data(self, **kwargs):
if context['is_valid']:
context = super().get_context_data(**kwargs)
context.update({'service_active': 'Active'})
return context
Personally, I’ve never implemented context updates like this. From what I’m seeing right now (this is my opinion of course), I don’t see the need for the BaseContext view. You could just as easily check the request cookies in the Services class and add the logic in there. Now if this logic is being repeated over and over again then I can understand this because you’ve essentially made a mixin.
I have nearly 30 view which all of them using same logic that’s way I am using BaseContext.
Okay, then that make’s perfect sense! That’s why I tried to preface my previous comment with “From what I’m seeing now…” In that case, I think this is effective.
I guess another option would be to just create a function that returns True/False depending on the status of the request.COOKIES.get('token')
. You could just check the return value of the function call to determine if you update service_active
to Active
.