【问题标题】:Django: Form save methodDjango:表单保存方法
【发布时间】:2013-08-25 07:44:27
【问题描述】:

我有一个表格,处理不同的模型并使用一个直通(中间)模型:

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)

我想在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()

【问题讨论】:

    标签: django django-forms save models


    【解决方案1】:

    只需在创建course 对象之后调用创建course 对象的代码即可。

    问题是,Course 模型中的ForeignKey customer 是必需的,而您在创建对象时没有设置该字段。

    我在代码中修复了一些其他小问题。 .

    def save(self):
        data = self.cleaned_data
    
        course_booking = None
        if self.cleaned_data['course']:
            crs = self.cleaned_data['course']
            course_booking = CourseBooking(course=crs)
            course_booking.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()
    
        course = CourseBooking.objects.create(course=data['course'], customer = cust)
        if course_booking:
            course.booking = course_booking
    
        #course.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()
    

    另外,我会将这个对象创建逻辑放在视图中,而不是 model_form 的 save 方法。

    【讨论】:

    • 请注意 save() 需要一个可选的 commit arg ;你应该处理它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2014-05-19
    • 2017-04-18
    相关资源
    最近更新 更多