Unable to post data to foreign key table in Django

I am an absolute beginner to Django and I am trying to check the POST method by populating the value to the foreign key table. I have two tables. Please guide me on where I am wrong.

  1. Table for Category that has 2 entries, i.e., Coffee(PK = 1) and Desserts (PK = 2)
  2. Table for Items

enter image description here

From models.py:

class Category(models.Model):
    cId = models.AutoField(primary_key=True)
    categoryName = models.CharField(max_length=20, unique=True)

    def __str__(self):
        return self.categoryName
        # return[self.categoryName, self.cId]
        # return self.cId
class Item(models.Model):
    Id = models.AutoField(primary_key=True)
    itemName  = models.CharField(max_length=30,unique=True)
    cId = models.ForeignKey(Category,on_delete=CASCADE)

From views.py:
def main(request):
return render(request, "index.html")

def send(request):
    if request.method == "POST":
        a = request.POST.get("a");
        b = request.POST.get("b");
        obj = Item(itemName = a, cId =b);
        return HttpResponse("sent")
        return HttpResponse("form submission failed")

From urls.py(app):

urlpatterns = [
    path('', views.main, name="main"),
    path('send', views.send, name='send')

From HTML:

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% load static %}

    <link rel="stylesheet" href="{% static 'css.css' %}">


    <div class = "container">
        <form method = "post" action = "send" class = "form">
            {% csrf_token %}
            <label for="a">Item Name</label>
            <input type="text" name="a" id="a" maxlength="30">
            <label for="b">PASS FOREIGN KEY--CATEGORY ID</label>
            <input type="number" name="b" id="b" maxlength="5">
            <button type="submit">SUBMIT</button>



    <script src="{% static 'js.js' %}"></script>


I am unable to populate the Item table with the following entry:
enter image description here

I am unable to resolve the following error:
enter image description here

>Solution :

cId expects a Category object, but you have given it '1'. If you want to specify the primary key instead for a ForeignKey named foo, you use foo_id, so in this case cId_id:

def send(request):
    if request.method == 'POST':
        a = request.POST.get('a')
        b = request.POST.get('b')
        obj = Item(itemName=a, cId_id=b)
        return HttpResponse("sent")
        return HttpResponse("form submission failed")

Leave a Reply