Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Forms Model Forms Editing Questions

Lars Wettmann
Lars Wettmann
15,376 Points

Order of "get_context_data" and changing model in class based views?

Hey guys,

I want to change this form into a class based view https://teamtreehouse.com/library/django-forms/model-forms/editing-questions . I can see that set_question_type is called and self.model and self.fields are updated cause it prints out "set to TF" in the console.

On the page itself, the form stays empty though and is not updated.

Any tipps?

class QuestionUpdateView(LoginRequiredMixin, UpdateView):
    question_type       =   ""
    pk_url_kwarg        =   "question_pk"
    context_object_name =   "question"
    fields              =   ()
    model               =   models.Question

    def set_question_type(self, question_type):
        if question_type == 'tf': 
            self.model      =   models.TrueFalseQuestion
            self.fields     =   ('quiz','order', 'prompt', 'correct_answer')
            print("set to TF")
        else:
            self.model      =   models.MultipleChoiceQuestion
            self.fields     =   ('quiz','order', 'prompt', 'shuffle_answers')
        return True

    def get_context_data(self, **kwargs):
        context             =   super().get_context_data(**kwargs)
        if hasattr(context['question'], 'truefalsequestion'):
            self.set_question_type('tf')
        else:
            self.set_question_type('mc')
        context['quiz']     =   models.Quiz.objects.filter(id=self.kwargs['quiz_pk']).first()
        return context