Django | Decimal Field是必需的,即使我将它设置为NULL=True



我试着用django玩一点,但我遇到了问题…我有一个不需要的十进制字段,所以我将其设置为"blank=True"one_answers"零= True"。但它仍然说这是必需的:(

我也做了所有的迁移。

这是我的models.py

from django.db import models
weightUnit = {
('kg' , 'kilogram'),
('g', 'gram'),
('t', 'tons'),
('n', '-'),
}
class Product(models.Model):
pname = models.CharField(
max_length=50,
)
pdesc = models.TextField(
max_length=5000,
)
pprice = models.DecimalField(
max_digits=6,
decimal_places=2,
)
psn = models.CharField(
max_length = 30,
null=True,
blank=True,
)
pweightunit = models.CharField(
choices=weightUnit,
default='n',
null=True,
blank=True,
max_length=5,
)
pweight = models.DecimalField(
null=True,
blank = True,
max_digits=10000,
decimal_places=2,
)
plimage = models.ImageField(
blank=True,
null=True,
)

这是我的表单。py

from django import forms
from .models import weightUnit
class RawProductForm(forms.Form):
name = forms.CharField(label="Name")
desc = forms.CharField(label="Beschreibung")
price = forms.DecimalField(label="Stückpreis")
sn = forms.CharField(label="Seriennummer")
weightunit = forms.ChoiceField(choices=weightUnit, label="Gewichteinheit")
weight = forms.DecimalField(label="Gewicht")
image = forms.ImageField(label="Bild")

这是我的观点。py

def product_add(request):
pf = RawProductForm()
if request.method == "POST":
pf = RawProductForm(request.POST)
if pf.is_valid():
print(pf.cleaned_data)
Product.objects.create(**pf.cleaned_data)
else:
print(pf.errors)

context = {
"productform" : pf,
}
return render(request, "product_add.html", context)

您正在使用一个简单的Form,而不是ModelForm[Django-doc],这意味着它根本不会检查模型。它将简单地呈现一个表单。ModelForm将检查模型,并在此基础上构建一个表单,您可以自定义。

class RawProductForm(forms.ModelForm):
class Meta:
model = Product
labels = {
'name': 'Name',
'desc': 'Beschreibung',
'price': 'Stückpreis',
'sn': 'Seriennummer',
'weightunit': 'Gewichteinheit',
'weight': 'Gewicht',
'image': 'Bild',
}

AModelForm也有.save(…)方法[Django-doc],它根据表单中的数据创建一个模型对象,并将其保存到数据库中。