Получение ввода от пользователя для использования в представлении на основе классов django

У меня есть следующий код:

class ObjectiveCreate(LoginRequiredMixin, UserPassesTestMixin, CreateView):

model = Objective
form_class = ObjectiveCreateForm
template_name = "internalcontrol/objective_create_form.html"

# Check that user is a consultant
def test_func(self):
    user = self.request.user
    return user.is_consultant

# Get user profile and entity and inject identity and entity into ObjectiveCreateForm
def form_valid(self, form):
    user = self.request.user
    profile = UserProfile.objects.get(user=user)
    entity = profile.entity
    new_profile = UserProfile.objects.get(user=user, entity=entity)
    form.instance.consultant = new_profile
    form.instance.entity = entity
    return super().form_valid(form)

# Enable use of self.request in form
def get_form_kwargs(self):
    kwargs = super(ObjectiveCreate, self).get_form_kwargs()
    kwargs["request"] = self.request
    return kwargs

Хорошо работает, когда консультант работает только с одной организацией.

В каждой структуре консультант имеет только один профиль, и поэтому профиль может быть уникально связан с соответствующей структурой.

Проблема возникает, когда консультант работает с более чем одной организацией. Это то, что я хотел бы решить с помощью пересмотренного кода.

Я не могу продвинуться дальше строки ниже с elif:

# Get user profile and entity and inject identity and entity into ObjectiveCreateForm
def form_valid(self, form):
    user = self.request.user
    if len(UserProfile.objects.filter(user=user)) == 1:
        # As mentioned above, this section of the code works well.
        profile = UserProfile.objects.get(user=user)
        entity = profile.entity
        new_profile = UserProfile.objects.get(user=user, entity=entity)
        form.instance.consultant = new_profile
        form.instance.entity = entity
        return super().form_valid(form)
    elif len(UserProfile.objects.filter(user=user)) > 1:
        # This is the section I struggle with
        # The UserProfile.objects.filter(user=user) queryset would have the multiple profiles.
        # There is a UserProfile ListView which can be filtered by user.
        # I would like the user to be able to choose one profile. (How do I provide a form for doing so?)
        # The users'/'s choice needs to fed into the line below.
        profile = UserProfile.objects.get(user=user)
        entity = profile.entity
        new_profile = UserProfile.objects.get(user=user, entity=entity)
        form.instance.consultant = new_profile
        form.instance.entity = entity
        return super().form_valid(form)
    else:
        messages.info(self.request, 'You do not have the required profile.')
Вернуться на верх