Django 使用 ModelMultipleChoiceField 保存 ManyToManyField 模型

Django save ManyToManyField Model with ModelMultipleChoiceField

所以我知道有几个类似的问题,但 none 的解决方案对我有用。我试过 save(commit=false) 和 save_m2m 以及其他一些东西,但我得到了错误

NOT NULL constraint failed: home_services.managers_id

无论如何,这是我的代码: views.py

def service(request):
    if request.user.is_authenticated:
        if request.method == 'POST':    #Create Service
            form = CreateServiceForm(request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/service')     #Later change this to redirect to server page
        else:
            form = CreateServiceForm()
            args = {'user': request.user, 'form': form}
            return render(request, 'service.html', args)
    else:
        return HttpResponseRedirect('/feed')

models.py

class Services(models.Model):
    name = models.CharField(max_length=100, default='')
    description = models.CharField(max_length=500, default='')
    owner = models.OneToOneField(User, on_delete=models.CASCADE)
    managers = models.ForeignKey(User, related_name="managers", on_delete=models.CASCADE)
    members = models.ManyToManyField(User, related_name="members")

    def __str__(self):
        return str(self.name) + ": id" + str(self.id)

forms.py

class CreateServiceForm(forms.ModelForm):
    owner = forms.ModelChoiceField(queryset=User.objects.all())
    members = forms.ModelMultipleChoiceField(queryset=User.objects.all())

    class Meta:
        model = Services
        fields = [
            'name',
            'description',
            'owner',
            'members',
        ]

我希望用户能够创建服务和 select 1 个或多个默认 django 用户模型中的成员。

I want the user to be able to create a service and select 1 or more members that is in the default django User model.

您未提供 managers,根据当前配置,这是不允许的。

所以,改变:

managers = models.ForeignKey(
    User, 
    related_name="managers", 
    on_delete=models.CASCADE,
)

收件人:

managers = models.ForeignKey(
    User, 
    related_name="managers", 
    on_delete=models.CASCADE,
    blank=True,
    null=True,
)

您可能想阅读有关 blank and null 的更多信息。