django - 姜戈 | 即使我将其设置为 NULL=True 也需要十进制字段
问题描述
我试图用 django 玩一点,但我遇到了问题......我有一个不需要的十进制字段,所以我将它设置为“blank = True”和“null = 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,
)
这是我的forms.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)
解决方案
您正在使用 simple Form
,而不是ModelForm
[Django-doc],这意味着它根本不会检查模型。它只会呈现一个表单。AModelForm
将检查模型并根据您可以自定义的形式构建一个表单。
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],它根据表单中的数据创建模型对象并将其保存到数据库中。
推荐阅读
- linux - 变量/参数扩展中的字符串项
- python - 由于 RuntimeWarning,solve_ivp 出现 ValueError:power 中遇到的值无效
- php - 数据库行未在 HTML 表中完全显示
- python - 如何根据给定的行值保留列
- ios - Today Widget 无法使用特定的代码行加载
- video - 是否可以使用 ffmpeg 垂直旋转 showwaves(或 showfreqs)覆盖?
- ag-grid - ag-grid 中的单选按钮
- php - 获取集合内对象的值
- reporting-services - 如何计算 SSRS 查询中的周转时间?
- batch-file - Forfiles 对待瑞典语的奇怪行为