无法使用inlineformset工厂将数据保存到模型外键(具有OneToOne关系)
创建inlineformset,然后创建视图以从表单集中捕获数据(它具有OneToOne关系)
models.py
class Bed(models.Model):
bed_no = models.CharField(primary_key=True,max_length=10, blank=True)
room_no = models.ForeignKey('Room', on_delete=models.SET_NULL, null=True)
----- and so on
class Guest(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
allotted_bed = models.OneToOneField(Bed,on_delete=models.SET_NULL, null = True)
-------- and so on
forms.py
GuestFormSet = inlineformset_factory(Bed, Guest,
fields='__all__',can_delete=False)
views.py
def guestinline(request, pk):
allotted_bed = Bed.objects.get(bed_no=pk)
if request.method == 'POST':
formset = GuestFormSet(request.POST,request.FILES, instance = allotted_bed)
if formset.is_valid():
formset.save()
return HttpResponse('Sucess')
else:
print(formset.errors)
else:
formset=GuestFormSet(instance=allotted_bed)
return render(request,'add_guest.html',{'formset':formset})
add_guest.html
<body>
<form>
{{formset.as_p}}
<button>Save</button>
</form>
</body>
预期输出:
Success
实际结果:
[04/May/2019 21:13:01] "GET /pgmanagement/add/6-B/?guest-TOTAL_FORMS=1&guest-INITIAL_FORMS=0&guest-MIN_NUM_FORMS=0&guest
-MAX_NUM_FORMS=1&guest-0-first_name=Siddu&guest-0-last_name=Saida&guest-0-mobile=123456790&guest-0-parent_name=saida&gue
st-0-dob=1992-02-06&guest-0-permenent_address=qwertyuiop%0D%0Alkjhgfdsa%0D%0A%3Blkjhgfds&guest-0-res_telephone=&guest-0-
date_of_admission=2019-05-02&guest-0-email_id=siddu%40gmail.com&guest-0-emergency_contact=&guest-0-relation=&guest-0-hig
her_degree=&guest-0-purpose_of_stay=&guest-0-office_address=&guest-0-office_telephone=&guest-0-id_proof_type=&guest-0-id
_proof_no=&guest-0-id_proof=&guest-0-photo=&guest-0-local_address_proof=&guest-0-amount_paid=0&guest-0-sharing_type=0&gu
est-0-allotted_bed=6-B&guest-0-id= HTTP/1.1" 200 4006