Создание элемента "многие ко многим" в линии из формы django

I have to two models Directors and JobProject. A JobProject can have multiple directors through a many-to-many relationship. Currently, when I create a new JobProject I choose from the directors I have saved who the director will be.

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

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

  1. Start entering a JobProject details.
  2. If the director already exist in the DB - Great
  3. If the director doesn't exist, allow users to enter the details of a new director object (probably using Java? ) 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'})

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