Issue
models.py:
from django.db import models
class Line(models.Model):
text = models.CharField(primary_key=True, max_length=255)
class Line2 (models.Model):
text_line = models.ForeignKey ("Line", primary_key = True)
views.py:
from django.core.context_processors import csrf
from django.shortcuts import render
import datetime
from models import Line, Line2
def test_page (request):
if 'uid' in request.POST:
user_id = request.POST['uid']
line_query = Line.objects.get (text = user_id)
new_entry = Line2 (text_line_id = line_query)
new_entry.save()
return render(request, "templateFiles/testPage1.html", {"page_result":"Data Entered"});
else:
return render(request, "templateFiles/testPage1.html")
template:
<div id = "header">
{{ page_result }}
<form action="http://127.0.0.1:8000/test_page/" method = "POST">
{% csrf_token %}
<input type="text" id="uid" name="uid" />
<input type="submit" id="submit" value="Submit" />
</form>
</div>
The data which I'm sending exists in the parent key, but I'm getting
IntegrityError
(1452, 'Cannot add or update a child row: a foreign key constraint fails (
tempDB
.testDBProjectApp_line2
, CONSTRAINTtext_line_id_refs_text_f741df88
FOREIGN KEY (text_line_id
) REFERENCEStestDBProjectApp_line
(text
))')
My Database Parent Table "line" is as follows:
mysql> select * from testDBProjectApp_line;
+-------+
| text |
+-------+
| test1 |
| test2 |
+-------+
Solution
You shouldn't assign the Line
instance to text_line_id
as you are currently doing.
You should either do
new_entry = Line2(text_line=line_query)
or
new_entry = Line2(text_line_id=line_query.text)
Answered By - Alasdair
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.