I have a CBV based on a TemplateView
It has a post(self) method to access user input.
Also, it has a template_name property which should be populated with data from post().
No Django models or forms are used here.
Attempt to extract data within post method:
# views.py
class ReturnCustomTemplateView(TemplateView):
def post(self, *args, **kwargs):
chosen_tmplt_nm = self.request.POST.get('tmplt_name')
print(chosen_tmplt_nm) # correct value.
# how do I use it outside this method? (like bellow)
template_name = chosen_tmplt_nm
... or is there any other way I can get the data from request.POST without def post()?
Thanks in advance!
CodePudding user response:
You can override the get_template_names()
method [Django-doc] which returns an iterable (for example a list) of template names to search for when determining the name of the template, so:
class ReturnCustomTemplateView(TemplateView):
def get_template_names(self):
return [self.request.POST.get('tmplt_name')]
def post(self, *args, **kwargs):
return self.get(*args, **kwargs)
I would however advise to be careful with this: a POST request could be forged, so a hacker could make a POST request with a different template name, and thus try to obtain for example the content of the settings.py
file or another file that contains sensitive data.