I am trying to get the values from Centre model via SubCentre model.
Using the subcentre ‘pk’ I am trying to fetch the Centre model data to auto-populate a form.
models.py
class Centre(models.Model):
Ccode = models.AutoField(primary_key=True)
Cname = = models.CharField(max_length=50, blank=True, null=True)
.....
def __str__(self):
return str(self.Ccode)
class SubCentre(models.Model):
Ccode = models.ForeignKey(Centre, blank=True, null=True, on_delete=models.SET_NULL, to_field="Ccode", related_name="Ccode")
Cname = models.CharField(max_length=50, blank=True, null=True) # holds Cname value of Centre
name = models.CharField(max_length=50, blank=True, null=True)
...............
def __str__(self):
return str(self.name)
class StudEntry(models.Model):
Ccode = models.ForeignKey(Centre, blank=True, null=True, on_delete=models.SET_NULL, to_field="Ccode", related_name="Ccode")
...........
forms.py
class StudentEntryForm(forms.ModelForm):
class Meta:
model = StudEntry
fields = "__all__"
views.py
def StudentEntry(request,pk):
subcentre = SubCentre.objects.get(pk=pk)
centre = Centre.objects.get(Ccode=subcentre.Ccode) # <= error is shown in this line
form = StudentEntryForm(request.POST or None, instance=subcentre)
if request.method == "POST":
if form.is_valid():
book = form.save(commit=False)
book.CCode = subcentre.Ccode
# book.zone = centre.zone
book.Cname = subcentre.Cname
book.save()
return redirect('subcentre-list')
else:
return render(request,"Students/CreateEntry.html",{'form':form,
'subcentre':subcentre, 'centre':centre})
context = {
'form':form,
'subcentre':subcentre,
'centre':centre
}
return render(request,"Students/CreateEntry.html",context)
urls.py
urlpatterns = [
path('<pk>/',StudentEntry,name='book-entry')
]
But getting the error as below,
Unable to fix the issue. Request help on the same. - Thank you!
Django Version: | 4.1 |
---|---|
Exception Type: | TypeError |
Exception Value: | Field ‘Ccode’ expected a number but got <Centre: 634>. |
Exception Location: | F:\Program Files\Python310\lib\site-packages\django\db\models\fields_init_.py, line 2020, in get_prep_value |
-
The above exception (int() argument must be a string, a bytes-like object or a real number, not ‘Centre’) was the direct cause of the following exception:
-
F:\Program Files\Python310\lib\site-packages\django\core\handlers\exception.py
, line 55, in inner
in the following line of the above view,
centre = Centre.objects.get(Ccode=subcentre.Ccode)