首页 > 解决方案 > 姜戈 | 即使我将其设置为 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)

标签: djangomodeldecimal

解决方案


您正在使用 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],它根据表单中的数据创建模型对象并将其保存到数据库中。


推荐阅读