列中的Django IntegrityError空值" author_id"违反非空约束

时间:2017-12-04 05:59:26

标签: python django postgresql django-forms django-views

我正在尝试保存一个用户输入的表单。我收到了诚信错误。有人可以帮帮我吗?我看到人们使用了request.user.username,但我不知道如何在我的表单中使用它。请不要介意代码,因为我仍在努力弄清楚Django中的内容。

以下是我的文件:

models.py

class CommonModel(models.Model):

    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=400)
    comments = models.TextField(blank=True)
    requirements = JSONField(default = {})
    specs = JSONField(default= {})
    created_date = models.DateTimeField(default=timezone.now)
    updated_date = models.DateTimeField(blank=True, null=True)

    class Meta:
       abstract = True

    def update(self):
        self.updated_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title


class Item(CommonModel):

    HW = 'HW'
    NW = 'NW'
    SW = 'SW'
    VM = 'VM'
    WI = 'WI'
    SI = 'SI'
    ITEM_TYPES = (
        (HW, 'Hardware'),
        (NW, 'Network'),
        (SW, 'Software'),
        (VM, 'Virtual Machine'),
        (WI, 'Work Item'),
        (SI, 'Support Item'), 
    )

    UNIT_LOE = 'LOE'
    UNIT_USD = 'USD'
    UNIT_TYPES = (
        (UNIT_LOE, 'LOE,MD'),
        (UNIT_USD, 'USD'),
    )

    item_type = models.CharField(default='HW', max_length=5, choices=ITEM_TYPES)
    unit_type = models.CharField(default='USD', max_length=5, choices=UNIT_TYPES)
    otc_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
    annual_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
    gp_code = models.TextField(default='Unknown')
    class Meta:
       abstract = True

class ItemTemplate(Item):
    pass
   # Need ID here to relate to estimate

class ItemObject(Item):
    pass

这是我的admin.py

class CommonAdmin(admin.ModelAdmin):

    formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
    }

    def otc_price(self,obj):       
        return json_prettified(obj.otc_price)
    def annual_price(self,obj):       
        return json_prettified(obj.annual_price)

from reversion.admin import VersionAdmin

@admin.register(ItemTemplate)
class ItemTemplateAdmin(VersionAdmin):
     list_display = ('title', 'item_type', 'unit_type', 'otc_price','annual_price')
     formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
     }

@admin.register(ItemObject)
class ItemObjectAdmin(VersionAdmin):
     list_display = ('title', 'item_type', 'unit_type', 'otc_price','annual_price')
     formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
     }

最后是views.py。

def order_create(request):
        cart = ItemObject.objects.all()

        if request.method == 'POST':
            form = ItemObjectCreateForm(request.POST)
            if form.is_valid():
                form.save()
                for item in cart:
                    annual_price = 122
                    otc_price=100
                    # Logic to calculate the price and put it in estimate table
                    ItemObject.objects.create(
                                             requirements=item.requirements,
                                             specs=item.specs,
                                             annual_price = annual_price,

                    )
                # clear the cart
                #cart.clear()
                order_created()
                # redirect to the payment
                return redirect('success.html')

        else:
            form = ItemObjectCreateForm()
        return render(request,
                      'index.html',
                      {'cart': cart, 'form': form})

这里我试图将数据存储到ItemObject,但在提交表单时,我收到错误。

IntegrityError: null value in column "author_id" violates not-null constraint
DETAIL:  Failing row contains 

我的forms.py也如下所示

class ItemObjectCreateForm(forms.ModelForm):
    class Meta:
        model = ItemObject
        fields = ['title','requirements', 'gp_code', 'specs','author', 'item_type', 'unit_type','comments', 'id'
                  ]

附加数据库 enter image description here

2 个答案:

答案 0 :(得分:1)

表单保存时,set commit argument为false以防止对象立即保存,

item = form.save(commit=False)
item.author = request.user
item.save()

并修改

ItemObject.objects.create( author=request.user, requirements=item.requirements, specs=item.specs, annual_price = annual_price, )

答案 1 :(得分:0)

var dataObject = graphDataObject.filter(function(el){ return el.timestamp == seconds && el.value == currentValue; //you can check only one object if you want here }); if(dataObject.length > 0) { //the object exists in the array } else{ graphDataObject.push({timestamp : seconds, value : currentValue}); //push object to the array. } 的定义中,您要求CommonModel不为空。那是对的吗?每个author的实例都必须有CommonModel吗?如果没有,您可以更改定义以允许空值:

author