I have a CRUD site and a model form (PenForm). One field (shelter) is a foreign key to another model. It shows on the form and all other fields are submitting and show in the DB - except this one. The field shows on the form as a select list drop down and source HTML looks ok. Any help appreciated…
Model:
class Pen(models.Model):
shelter = models.ForeignKey(Shelter, on_delete=models.CASCADE, null=True)
intaker = models.ForeignKey(User, default=None, on_delete=models.CASCADE, null=True)
child = models.ForeignKey(human, default=None, on_delete=models.CASCADE, null=True)
...
Form:
class PenForm(forms.ModelForm):
class Meta:
model = Pen
fields = ['shelter','occupied',...]
View:
@login_required
@transaction.atomic
def child_add(request, id):
ownr = User.objects.get(id=id)
fnm = ownr.first_name
lnm = ownr.last_name
loc = ownr.profile.location
if request.method == 'POST':
human_form = HumanForm(request.POST, request.FILES)
pen_form = PenForm(request.POST)
if human_form.is_valid() and pen_form.is_valid():
usr_curr = User.objects.get(id=id)
prf_curr = Profile.objects.get(user_id=usr_curr.id)
prf_locid_curr = prf_curr.location_id
prf_loc_curr = prf_curr.location_id
human_form.save(commit=False)
human_form.instance.intaker = request.user
human_form.instance.human = usr_curr
human_form.instance.location = prf_curr.location
human_form.save()
hum_curr = Human.objects.last()
messages.success(request, f"Human data was saved successfully.")
pen_form.save(commit=False)
pen_form.instance.intaker = request.user
pen_form.instance.human = hum_curr
#pen_form.instance.shelter = pen_form.shelter # tried to explicitly add though should not have to...
pen_form.save()
return redirect('/intake/humans')
else:
human_form = HumanForm()
pen_form = PenForm()
context = {
'id': id,
'fnm': fnm,
'lnm': lnm,
'human_form': human_form,
'pen_form': pen_form,
}
return render(request, 'intake/human-add.html', context)
Thoughts? Any clues appreciated…