I'm wondering if it is possible to dynamically assign the template_name based on data provided to my class-based view using a form?

for example I have the following form page:


def form_generate_pdf(request, project_id):
   """Form to collect data to insert into PDF"""

   project = Project.objects.get(id=project_id)

   if request.method == 'POST':
      form = PDFForm(request.POST)
      if form.is_valid():
         request.session['field1'] = form.cleaned_data.get('field1')
         return redirect('myapp:generate_pdf')

      form = PDFForm()

   context = {
      'project': project,
      'form': form

And the page that generates the PDF:


class Generate_PDF(PDFTemplateView):
   """Generate a PDF using the values from form_generate_pdf"""

   filename = "test.pdf"
   # I want the field below to be dynamic depending on the value of field1 from the view form_generate_pdf
   template_name = "myapp/pdf.html"
   cmd_options = {
      'page-size': 'Letter',
      'viewport-size' : '1920x1080',
      'footer-left' : '[page]/[topage]',
      'no-outline' : True,

   def get_context_data(self, **kwargs):
      context = super(Generate_PDF, self).get_context_data(**kwargs)
      field1 = self.request.session['field1']
      context['field1'] = field1

I would say I'm intermediate with django but I'm still fairly new to python and django in general (~5 months of playing now), I don't seem to have enough understanding to figure out how to insert some logic into the Generate_PDF class to programatically select the template type. Something like:

if field1 = 'this':
   template_name = 'myapp/pdf_1.html'
   template_name = 'myapp/pdf_2.html'

The problem is my view can't seem to see the field1 variable.

Perhaps I am going about this the wrong way as well. I could have my form redirect to unique class based views I suppose, but even though that would solve my issue it feels very repetitive and incorrect to me.