Rohit Kumar
Rohit Kumar

Reputation: 725

Cannot assign : must be a instance Django foreign Key error

I have created a model and connected a foreign key with it, but when I save them I get an error Cannot assign "1": "SupplierBidModel.Load_ID" must be a "ShipperBoardModel" instance.

I am fairly new to Django, and even newer to Django interconnected models concept. Any idea why this is happening ?? I have no idea where to go from here as there are not many questions such as this on Google either.

My models.py

class ShipperBoardModel(models.Model):
    # Manufaturer_ID
    LoadID = models.AutoField(primary_key=True)
    From = models.CharField(max_length=100,null=True)
    To = models.CharField(max_length=100,null=True)
    Type = models.CharField(max_length=100,null=True)
    Length = models.CharField(max_length=100,null=True)
    Weight = models.CharField(max_length=100,null=True)
    Numberoftrucks = models.IntegerField(null=True)
    MaterialType = models.CharField(null=True,max_length=100)
    Loadingtime = models.DateTimeField(null=True)
    # Loadkey = models.ForeignKey()

    def _str_(self):
        return self.Origin
#
class SupplierBidModel(models.Model):
    BidID = models.AutoField(primary_key=True)
    Load_ID = models.ForeignKey(ShipperBoardModel,on_delete=models.CASCADE,default=3)
    Supplier_ID = models.ForeignKey(SupplierBoardModel,on_delete=models.CASCADE,default=3)
    Bid_amount = models.IntegerField(null=True)

  class Meta:
      unique_together = ('Load_ID', 'Supplier_ID')

Views.py

def suppliertablefun (request):  # function to display shipperboardmodel
    data = ShipperBoardModel.objects.all()

    if request.method == 'POST':
        forminput = BiddingForm(request.POST)
        if forminput.is_valid():
            forminput.save()

    forminput = BiddingForm(request.POST)
    return render(request, 'supplierboard/board.html', locals(), {'forminput': forminput})

PS: I am trying to prefill my form as such:

<form action="" method="post">
  {# <input type="hidden" value={{item.LoadID}} name="Load_ID" /> #}
  <input type="hidden" value={{item.LoadID}} name="Load_ID" />
  {{ forminput.Bid_amount }}
  <input type="submit" class="btn btn-primary" value="Submit"/>
</form>

I am trying to pass the current LoadID in the LoadID by using value = {{item.LoadID}} which is running because there a for loop in the template as such :

{% for item in data %}

Forms.py

class BiddingForm(forms.ModelForm):
    Bid_amount = forms.IntegerField()
    Load_ID = forms.IntegerField(widget=forms.HiddenInput())
    class Meta:
        model = SupplierBidModel
        exclude = ()

Ok so I just fixed that error by pass value={{LoadID}} instead of value={{item.LoadID}} and there is no error, but it is not saving anything to the database. What to do now ?

Upvotes: 1

Views: 2683

Answers (2)

gdef_
gdef_

Reputation: 1936

Somewhere in your code you are trying to assign a number (1) to SupplierBidModel.Load_ID, which is incorrect because you have the following in your SupplierBidModel:

Load_ID = models.ForeignKey(ShipperBoardModel,on_delete=models.CASCADE,default=3,related_name='load')

If you are creating the ShipperBidModel using a number to link the ShipperBoardModel then you need to get the corresponding object first, something along the lines of:

# ... you get load_id from the form
shipper_board = ShipperBoardModel.objects.get(pk=load_id)
# then you create the SupplierBidModel instance, adding the other fields that you want
SupplierBidModel.objects.create(LoadId=shipper_board)

Your LoadId is not an id, is an ShipperBoardModel object, so you need to assign the corresponding one.

Your naming convention is all over the place, model fields should be lowercase separated by underscores. Check the docs: Model style

Upvotes: 3

Exprator
Exprator

Reputation: 27503

well you have some problem in the model

class SupplierBidModel(models.Model):
    BidID = models.AutoField(primary_key=True)
    Load_ID = models.ForeignKey(ShipperBoardModel,on_delete=models.CASCADE,default=3,related_name='load')
    Supplier_ID = models.ForeignKey(SupplierBoardModel,on_delete=models.CASCADE,default=3,related_name='supplier')
    Bid_amount = models.IntegerField(null=True)

you cannot have more than one in a single model. for that you need related_name parameter

Upvotes: 1

Related Questions