Solution details

As you must have noticed, you can solve this using the solution given in the dynamic form generation pattern. You just need to pass request.user or any of their characteristics as a keyword argument to the form. I would recommend the latter to minimize the coupling between the view and the form.

As in the previous example, we need to show an additional checkbox to the user. However, this will be shown only if the user is a member of the "VIP" group.

Let's take a look at how the GenericFormView derived view passes this information to the form:

class GenericFormView(generic.FormView): 
    template_name = 'cbv-form.html' 
    form_class = PersonDetailsForm 
    success_url = reverse_lazy("home") 
 
    def get_form_kwargs(self): 
        kwargs = super().get_form_kwargs() 
        # Check if the logged-in user is a member of "VIP" group 
        kwargs["vip"] = self.request.user.groups.filter(
name="VIP").exists() return kwargs

Here, we are redefining the get_form_kwargs method that FormView calls before instantiating a form to return the keyword arguments. This is the ideal point to check whether the user belongs to the VIP group and pass the appropriate keyword argument.

As before, the form can check for the presence of the vip keyword argument (like we did for upgrade) and present a check box for upgrading to first class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.136.170