Django форма - какая форма/шаблон подходит для создания объекта многие-ко-многим inline

У меня есть две модели Directors и JobProject. JobProject может иметь несколько директоров через отношения "многие ко многим".

В настоящее время, когда я создаю новый JobProject, я выбираю из сохраненных директоров, кто будет директором. Однако я пытаюсь понять, как я могу закодировать форму/вид для создания JobProject, где я также могу создать директора в линию (в случае, если у меня нет директора, уже сохраненного в БД).

В идеале поток пользователей должен быть таким:

1) Start entering a JobProject details. 
2) If the director already exist in the DB, pick it.
3) If the director doesn't exist, allow users to enter the details of a new director object in-line
4) Users go ahead and finish entering JobProject details.
5) Users click save and the BE first save the new director and then save the new project with director pointing at the newly created director.

В основном я разобрался с 1,2,4,5, но не могу понять, как сделать 3. Есть помощь? Вот мой код на данный момент.

Модель

class Director(models.Model):
    ...
    name_surname = models.CharField(max_length=60)


class JobProject(models.Model):
    ...
    director = models.ManyToManyField(Director, blank=True, )

Форма

class DirectorForm(forms.ModelForm):
    class Meta:
        model = Director
        fields = '__all__'
        exclude = ('id', 'owner', 'matching_user')

class JobProjectForm(forms.ModelForm):
    class Meta:
        model = JobProject
        fields = '__all__'
        exclude = ('id', 'owner')
        ...

    def __init__(self, *args, **kwargs):

        ...

        if 'director' in self.data:
            self.fields['director'].queryset = Director.objects.all()
        elif self.instance:
            self.fields['director'].queryset = self.instance.director

** Просмотр**

def new_jobproject(request):
    form = JobProjectForm()
    if request.is_ajax():
        term = request.GET.get('term')
        source = request.GET.get('source')
        response_content = []

        ...

        elif source == 'director':
            directors_retrieved = Director.objects.filter(Q(name_surname__istartswith=term)
                                                        & (Q(owner__isnull=True) | Q(owner=request.user))
                                                            )
            response_content = list(directors_retrieved.values())
    
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = JobProjectForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            jobproject_added = form.save()
            jobproject_added.owner = request.user
            jobproject_added.save()

            # redirect to precedent url:
            return redirect('action:dashboard')
    # if a GET (or any other method) we'll create a blank form
    return render(request, 'action/forms/jobproject_form.html', {'form': form, 'source': 'new'})


Попытка использовать django-taggit: https://django-taggit.readthedocs.io/en/latest/ с django-autocomplete-light: https://django-autocomplete-light.readthedocs.io/en/master/taggit.html. С их помощью вы можете добавить новые отношения "многие ко многим" в форму.

Вернуться на верх