Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
        obj.save()
        
        return HttpResponse("sent")
    else:
        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">

<head>
    <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' %}">

    <title>CHECK-POST-METHOD</title>
</head>

<body>
    <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>

        </form>

    </div>

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

</html>

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)
        obj.save()
        
        return HttpResponse("sent")
    else:
        return HttpResponse("form submission failed")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading