[Answered ]-Passing a variable in get()

1👍

You need to override the dispatch method to check the user group and the get_context_data method to add the header to the context.

Your code should look something like this (I haven’t tested it):

class ItemCreate(CreateView):
    template_name = 'form/additem.html'
    model = Parts
    fields = ['number', 'item']
    success_url = reverse_lazy('parts_list')

    def form_valid(self, form):
        username = self.request.user.get_full_name()
        form.instance.user = username
        form.instance.desc = getDescFromDB(form.cleaned_data['number'])
        return super(ItemCreate, self).form_valid(form)
    
    def dispatch(self, request, *args, **kwargs):
        match checkUserGroup(self.request.user):
            case "Service":
                return redirect("/")
            case "Shop":
                return super().dispatch(request, *args, **kwargs)
                
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["name"] = getHeader('PartsForm')
        return context

Find more information about the dispatch method here and about adding extra context data here.

Leave a comment