所以我知道有一些类似的问题,但没有一个解决方案对我有用。我尝试了保存(提交=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',
]
我希望用户能够创建一个服务并选择默认 django 用户模型中的 1 个或多个成员。
我希望
用户能够创建一个服务并选择默认 django 用户模型中的 1 个或多个成员。
您没有提供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,
)
您可能想阅读有关空白和空值的更多信息。