私はフォームを持っており、さまざまなモデルで作業し、スルー (中間) モデルを使用しています。
class CourseBooking(BaseModel):
'''Intermediary model linking a person on a course with the related booking'''
course = ForeignKey('ScheduledCourse')
customer = ForeignKey('Customer')
booking = ForeignKey('GroupBooking', blank=True, null=True)
フォームはモデル フォームの代わりに基本的なフォームを使用しており、フィールドは手動で追加されています。
class CourseBookingForm(Form):
course = ModelChoiceField(queryset=ScheduledCourse.objects.all())
title = CharField(
max_length=255,
widget=Select(choices=TITLE_CHOICES),
required=False
)
gender = CharField(
max_length=255,
widget=Select(choices=GENDER_CHOICES),
required=False
)
first_name = CharField(max_length=255)
surname = CharField( max_length=255)
dob = DateField(required=False)
medical = CharField(required=False, widget = forms.Textarea(attrs={'rows': '4'}))
# miscellaneous notes
notes = CharField(required=False, widget = forms.Textarea(attrs={'rows': '4'}))
email = EmailField(required=False)
phone = CharField(required=False)
address = CharField(
max_length=8188,
widget=Textarea(attrs={'rows':'4', 'cols':'50'}),
required=False)
city = CharField(max_length=255, required=False)
county = CharField(
max_length=255, widget=Select(choices=COUNTY_CHOICES))
postcode = CharField(max_length=255, required=False)
country = CharField(
max_length=255,
widget=Select(choices=COUNTRIES), required=False)
データベースに保存する save メソッドを作成したいと考えてforms.py
います。私が現時点で持っているもの(これは間違っています)であり、エラーが発生します:IntegrityError: null value in column "customer_id" violates not-null constraint
def save(self):
data = self.cleaned_data
if self.cleaned_data['course']:
crs = self.cleaned_data['course']
course_booking = CourseBooking(course=crs)
course_booking.save()
course = CourseBooking.objects.create(course=data['course'])
course.save()
cust = Customer.objects.create(title=data['title'],
gender=data['gender'],
first_name=data['first_name'],
surname=data['surname'],
dob=data['dob'],
notes=data['notes'],
medical=data['medical'],
content_object=cust,
)
cust.save()
address = Address.objects.create(address=data['address'],
city=data['city'],
county=data['county'],
postcode =data['postcode'],
country=data['country'],
content_object=address,
)
address.save()
email = Email.objects.create(email=data['email'],
content_object=email)
email.save()
phone = Phone.objects.create(number=data['phone'],
content_object=phone)
phone.save()