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

Lars Wettmann
Lars Wettmann
15,376 Points

How to update model and fields in Class Based Views based on pk?

Hi guys,

I try to re-write this https://teamtreehouse.com/library/django-forms/model-forms/handling-multiple-form-classes to a class based view.

Basically what I am trying to do is get a "mc" or "tf" pk via the URL and change the model and fields of my CreateView based on that.

It seems that the question_type in get() can be found, but the models and fields don't get changed. I tried to look it up at CCBV but I cannot understand anything from that sort of documentation.

The pk is called "question_type". This is my View:

class QuestionCreateView(LoginRequiredMixin, mixins.PageTitleMixin, CreateView):
        #setting standard model and fields
    model       =   models.MultipleChoiceQuestion 
    fields      =   ('quiz','order', 'prompt', 'shuffle_answers')
    page_title          =   "Add a new Question"
    context_object_name =   "quiz"
    template_name       =   "courses/question_form.html"

    def get_context_data(self, **kwargs):
        ''' only used for the page title '''
        context             =   super().get_context_data(**kwargs)
        context['quiz']     =   models.Quiz.objects.filter(id=self.kwargs['quiz_pk']).first()
        return context

    def get(self, request, *args, **kwargs):
        get     =   super().get(request, args, kwargs)
        question_type = kwargs.get('question_type')
        self.set_question_type(question_type)
        return get

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

I'm happy for every help. I'm struggling on this topic since days. Thanks in advance.

1 Answer

Lars Wettmann
Lars Wettmann
15,376 Points

Okay, miraculously, I found the answer myself just now. For everyone who's bumping into the same problem:

Basically, all control structures need to go into a separate method. You override the dispatch() method, get the kwargs, and call your own method to run the control structure and update the class attributes.

class QuestionCreateView(LoginRequiredMixin, mixins.PageTitleMixin, CreateView):
    question_type       =   ""
    page_title          =   "Add a new Question"
    context_object_name =   "quiz"
    template_name       =   "courses/question_form.html"

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

    def get_context_data(self, **kwargs):
        ''' only used for the page title '''
        context             =   super().get_context_data(**kwargs)
        context['quiz']     =   models.Quiz.objects.filter(id=self.kwargs['quiz_pk']).first()
        return context

    def dispatch(self, request, *args, **kwargs):
        question_type = kwargs.get('question_type')
        self.set_question_type(question_type)
        # call the view
        return super().dispatch(request, *args, **kwargs)