[Fixed]-Get instance from model to save to foreignkey field

1đź‘Ť

Found the problem, guess it’s my fault for not including forms.py in the question

THE WRONG ONE

class TempCart(forms.ModelForm):
    Product_ID = forms.CharField(max_length=80, label="Product ID")
    HowMany = forms.IntegerField(label='HowMany')
    DateSubmit = forms.DateTimeInput()
    class Meta:
        model = Cart
        fields = ["Product_ID","HowMany","DateSubmit",]

Problem was with the fields

all it takes to fix the problem is deleting the “Product_ID”

fields = ["HowMany","DateSubmit",]

Thank you all for helping me

Cheers

but if it is not too much to ask can anyone explain why this is happening?
why do django decilne the “Product_ID” on the fields?

👤Samir Price

0đź‘Ť

For begining fix this little syntax mistake:
VarProductId = Product.objecrs.get(PId=”Product_ID”) *Product.objects.get

👤FirePower

0đź‘Ť

“Cannot assign “15”: “Cart.Product_ID” must be a “Product” instance.”

Above signifies that you are trying to insert a row in Cart table with Product_Id = 15. Since this is a foreign key, Product_Id should be present in class / table Product. First please insert the value in Product before inserting the row in class Cart. This should work.

👤Len

0đź‘Ť

There are a few this apart from the solution I want to mention:

  1. What I feel is somehow the web server you have started has not been
    refreshed. try restarting it if possible. Seems to me that is the
    issue here.
  2. If there is a spelling mistake in objecrs you will an exception stating is not a valid manager rather than 15.

  3. Try to log/print the type of VarProductId before assigning it.

  4. Don’t prefix Var for all variables. It is not the way to write clean code. Also everything in python is an object. So there is no
    sense in prefixing it var.

  5. After checking form.is_valid() always use form.cleaned_data to fetch the data you want. Not from request.

👤SomeTypeFoo

0đź‘Ť

Other than your objecrs typo, this code should run fine.

Try deleting your .pyc files (specifically views.pyc) and restarting your development server.

👤J. McBride

Leave a comment