Home > Enterprise >  Django IntegrityError (1048, "Column 'item_id_id' cannot be null")
Django IntegrityError (1048, "Column 'item_id_id' cannot be null")

Time:10-16

The error posted is Integrity Error 1048 column cannot be null IntegrityError at /Supply/supplyItems (1048, "Column 'item_id_id' cannot be null") Request Method: POST Request URL: http://127.0.0.1:8000/Supply/supplyItems Django Version: 4.1.1 Exception Type: IntegrityError Exception Value:
(1048, "Column 'item_id_id' cannot be null") Exception Location: C:\Users\63966\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\mysql\base.py, line 80, in execute Raised during: Supply.views.SupplyItem Python Executable: C:\Users\63966\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.6 Python Path:
['D:\CIT\3rd Year\IM 2\New ' 'folder\sarisaristoreproject\sarisaristoreproject\sarisaristoreproject', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\63966\AppData\Local\Programs\Python\Python310', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\lib\site-packages'] Server time: Sat, 15 Oct 2022 07:25:53 0000

Here is my models.py

class Supplier(models.Model):
    supplier_id = models.AutoField(primary_key=True)
    company_name = models.CharField(max_length=20, null=False)
    company_address = models.CharField(max_length=50, null=False)
    company_num = models.IntegerField(null=False)

    def __str__(self):
       return str(self.company_name)

class supplyItem(models.Model):
    item_id = models.ForeignKey('Items.Items', on_delete=models.CASCADE)
    supplier_id = models.ForeignKey(Supplier, on_delete=models.CASCADE)
    numOfItemsS = models.IntegerField()

Items model from different App:

class Items(models.Model):
   item_id = models.AutoField(primary_key=True)
   item_name = models.CharField(max_length=50, null=False)
   item_qty = models.IntegerField(null=False)
   item_prc = models.FloatField(null=False)
   purchase = models.ManyToManyField('registration.Customer', through='Purchase.purchasedItem', related_name='items', blank=True)
   sell = models.ManyToManyField('registration.Employee', through='Sell.sellItem', related_name='items', blank=True)

def __str__(self):
    return self.item_name

My views.py

class HomeView(View):
    template = 'supply.html'

    def get(self, request):
        return render(request, self.template)

class SupplyItem(View):
    template = 'SupplyItems.html'

    def get(self, request):
        form = SupplyItemForm()
        return render(request, self.template, {'form': form})

    def post(self, request):
        form = SupplyItemForm(request.POST)
        if form.is_valid():
            form.save()
        return render(request, self.template, {'form': form})

Forms.py

class SupplyItemForm(ModelForm):
    itemID = forms.ModelChoiceField(widget=forms.Select(), queryset=Items.objects.only('item_id'), label='Item name')
    supplierID = forms.ModelChoiceField(widget=forms.Select(), queryset=Supplier.objects.only('supplier_id'), label='Supplier Company')
    itemQty = forms.IntegerField(widget=forms.NumberInput, label='Quantity')

    def __init__(self, *args, **kwargs):  # constructor
        super(SupplyItemForm, self).__init__(*args, **kwargs)

    class Meta:
        model = supplyItem
        fields = ['itemQty', 'itemID', 'supplierID']

    def clean_itemQty(self):
        qty = self.data.get('itemQty')
        if int(qty) <= 0:
            raise ValidationError('Quantity must be a positive number!')
        else:
            return qty

    def clean_itemID(self):
        data = self.cleaned_data.get('itemID')
        if data == '':
            raise ValidationError('Please select a value!')
        return data

    def clean_supplierID(self):
        data = self.cleaned_data.get('supplierID')
        if data == '':
            raise ValidationError('Please select a value!')
        return data

My template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Supply Item</title>
</head>
<body>
    <h1>Supply Store Items</h1>
    <h2>Select Supplier and Items to Supply</h2>
    <hr/>
    <form method="post">
        {% csrf_token %}
         {{form.as_p}}
        <input type="submit" value="Add Store items">
    </form>
</body>
</html>

And the form when i run the server is this:

CodePudding user response:

In you model the field is named item_id but in your ModelForm the field is named itemID. The field names should be the same.

Rename the fields in your ModelForm so they match the Model.

  • Related