将 django 表单保存到 mssql 数据库时,将数据类型 nvarchar 转换为数字时出错
Getting error converting data type nvarchar to numeric while saving django form to mssql database
我正在将 django-pyodbc-azure 与 mssql 一起使用,并且我在 models.py:
中将一些字段设置为外键
class Production(models.Model):
date = models.CharField(max_length=10, null=True)
dateGr = models.DateField(auto_now=False, auto_now_add=False, null=True)
comName = models.CharField(max_length=100, null=True)
comId = models.ForeignKey(Company, on_delete=models.CASCADE, null=True)
prodName = models.CharField(max_length=100, null=True)
prodId = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
gradeId = models.ForeignKey(ProductGrade, on_delete=models.CASCADE, null=True)
gradeName = models.CharField(max_length=100, null=True)
gradeType = models.CharField(max_length=3, null=True)
gradeTypeId = models.ForeignKey(GradeType, on_delete=models.CASCADE, null=True)
qty = models.FloatField(null=True)
cap = models.FloatField(null=True)
designCap = models.FloatField(null=True)
plan = models.FloatField(null=True)
unitId = models.ForeignKey(QtyUnit, on_delete=models.CASCADE, null=True)
unit = models.CharField(max_length=20, null=True)
我的 forms.py 是这样写的:
class CreateProduction(forms.ModelForm):
class Meta:
model = Production
fields = ['date', 'comId', 'prodId', 'gradeId', 'gradeTypeId', 'unitId', 'qty']
widgets = {
'date': forms.TextInput(attrs={'class': 'form-control', 'name': 'tdate', 'id': 'input-tdate'}),
'comId': forms.Select(attrs={'class': 'form-control'}),
'prodId': forms.Select(attrs={'class': "form-control"}),
'gradeId': forms.Select(attrs={'class': 'form-control'}),
'gradeTypeId': forms.Select(attrs={'class': 'form-control'}),
'unitId': forms.Select(attrs={'class': 'form-control'}),
'qty': forms.NumberInput(attrs={'class': 'form-control', 'id': 'qty', 'type': 'number', 'value': '0'}),
}
def __init__(self, user, comId, *args, **kwargs):
super(CreateProduction, self).__init__(*args, **kwargs)
self.fields['comId'].queryset = Company.objects.filter(userId=user)
self.fields['prodId'].queryset = Product.objects.filter(comId=comId)
products = Product.objects.filter(comId=comId)
self.fields['gradeId'].queryset = ProductGrade.objects.filter(prodId__in=products)
处理将我的表单数据保存到数据库的函数如下:
@login_required(login_url='login')
@allowed_users(allowed_roles=['editor'])
def create_production(request):
print(request)
if request.method == 'POST':
comId = Company.objects.values_list('id', flat=True).get(userId=request.user)
form = CreateProduction(request.user, comId, request.POST)
if form.is_valid():
production = form.save(commit=False)
print(request.POST)
production.user = request.user
production.save()
return redirect('/')
else:
comId = Company.objects.values_list('id', flat=True).get(userId=request.user)
form = CreateProduction(request.user, comId)
return render(request, 'production/production_form.html', {'form': form})
当我从我的 forms.py 中删除与“unitId”相关的行时,整个代码工作得非常好,模板和数据被插入到数据库中。
但是当我添加与“unitId”相关的行时,我得到了这个错误:
('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type nvarchar to numeric. (8114) (SQLExecDirectW )')
我不明白“unitId”字段有什么问题
所以问题是日期的值,因为我的项目日期是波斯语,我必须在我的模型中将日期字段定义为 CharField,因为日期的值是波斯语数据库不接受该值,因为它是Unicode 所以我在 views.py 中添加了一行,如下所示:
production.date = unidecode(str(request.POST.get('date')))
这修正了错误。
我正在将 django-pyodbc-azure 与 mssql 一起使用,并且我在 models.py:
中将一些字段设置为外键class Production(models.Model):
date = models.CharField(max_length=10, null=True)
dateGr = models.DateField(auto_now=False, auto_now_add=False, null=True)
comName = models.CharField(max_length=100, null=True)
comId = models.ForeignKey(Company, on_delete=models.CASCADE, null=True)
prodName = models.CharField(max_length=100, null=True)
prodId = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
gradeId = models.ForeignKey(ProductGrade, on_delete=models.CASCADE, null=True)
gradeName = models.CharField(max_length=100, null=True)
gradeType = models.CharField(max_length=3, null=True)
gradeTypeId = models.ForeignKey(GradeType, on_delete=models.CASCADE, null=True)
qty = models.FloatField(null=True)
cap = models.FloatField(null=True)
designCap = models.FloatField(null=True)
plan = models.FloatField(null=True)
unitId = models.ForeignKey(QtyUnit, on_delete=models.CASCADE, null=True)
unit = models.CharField(max_length=20, null=True)
我的 forms.py 是这样写的:
class CreateProduction(forms.ModelForm):
class Meta:
model = Production
fields = ['date', 'comId', 'prodId', 'gradeId', 'gradeTypeId', 'unitId', 'qty']
widgets = {
'date': forms.TextInput(attrs={'class': 'form-control', 'name': 'tdate', 'id': 'input-tdate'}),
'comId': forms.Select(attrs={'class': 'form-control'}),
'prodId': forms.Select(attrs={'class': "form-control"}),
'gradeId': forms.Select(attrs={'class': 'form-control'}),
'gradeTypeId': forms.Select(attrs={'class': 'form-control'}),
'unitId': forms.Select(attrs={'class': 'form-control'}),
'qty': forms.NumberInput(attrs={'class': 'form-control', 'id': 'qty', 'type': 'number', 'value': '0'}),
}
def __init__(self, user, comId, *args, **kwargs):
super(CreateProduction, self).__init__(*args, **kwargs)
self.fields['comId'].queryset = Company.objects.filter(userId=user)
self.fields['prodId'].queryset = Product.objects.filter(comId=comId)
products = Product.objects.filter(comId=comId)
self.fields['gradeId'].queryset = ProductGrade.objects.filter(prodId__in=products)
处理将我的表单数据保存到数据库的函数如下:
@login_required(login_url='login')
@allowed_users(allowed_roles=['editor'])
def create_production(request):
print(request)
if request.method == 'POST':
comId = Company.objects.values_list('id', flat=True).get(userId=request.user)
form = CreateProduction(request.user, comId, request.POST)
if form.is_valid():
production = form.save(commit=False)
print(request.POST)
production.user = request.user
production.save()
return redirect('/')
else:
comId = Company.objects.values_list('id', flat=True).get(userId=request.user)
form = CreateProduction(request.user, comId)
return render(request, 'production/production_form.html', {'form': form})
当我从我的 forms.py 中删除与“unitId”相关的行时,整个代码工作得非常好,模板和数据被插入到数据库中。 但是当我添加与“unitId”相关的行时,我得到了这个错误: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type nvarchar to numeric. (8114) (SQLExecDirectW )') 我不明白“unitId”字段有什么问题
所以问题是日期的值,因为我的项目日期是波斯语,我必须在我的模型中将日期字段定义为 CharField,因为日期的值是波斯语数据库不接受该值,因为它是Unicode 所以我在 views.py 中添加了一行,如下所示:
production.date = unidecode(str(request.POST.get('date')))
这修正了错误。