Django ModelForm自定义日期字段

时间:2019-05-16 18:23:46

标签: django modelform

我正在尝试创建一个预订表单,该表单在发布时为模型预订创建一个对象。我正在使用自定义的datepicker小部件来选择吃的食物,但是我也在使用ModelForms。

问题是,如果在forms.py的元字段列表中没有列出“日期”,则该表单将不会在发布时查找输入的日期字段。但是,如果我在forms.py Modelform的元字段中包含“日期”,则它会出错并说“日期字段不能为空”,即使它不是空白...

forms.py

class ReservationForm(forms.ModelForm):

    date = forms.DateField(
        widget=DatePickerInput(format='%m/%d/%Y')
        )
    def clean_date(self):
        data = self.cleaned_data['date']

        # Check if a date is not in the past.
        if data < datetime.date.today():
            raise ValidationError(_('Invalid date - reservation in past'), code='invalid')
            messages.danger(request, "Reservation Created")
            print('ERROR')


            # Remember to always return the cleaned date.
            return data

    class Meta:
        model = Reservation
        fields = ('reservation_time', 'people', 'name', 'email', 'phone') # REMOVED 'date'

views.py

def reservationFormView(request):
    #reservation = create(Reservation)
        # If this is a POST request then process the Form data
    if request.method == 'POST':
        # Create a form instance and populate it with data from the request (binding):
        form = ReservationForm(request.POST)

        # Check if the form is valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required

            reservation = form.save(commit=False)
            reservation.ReservationEmail = form.cleaned_data['email']
            reservation.ReservationName = form.cleaned_data['name']
            reservation.ReservationPeople = form.cleaned_data['people']
            reservation.ReservationTime = form.cleaned_data['reservation_time']
            reservation.date = form.cleaned_data['date']
            print( reservation.date)
            #reservation.created_time = timezone.now()
            reservation.save()

                # redirect to a new URL:
            return HttpResponseRedirect('/reservation-confirmation/')

        # If this is a GET (or any other method) create the default form.
    else:
        form = ReservationForm()

    return render(request, 'home/reservation_form.html', {'form': form, })

models.py

class Reservation(BaseModel):
    class Meta:
        verbose_name_plural = "Reservations"

    TIME_CHOICES = (
...
    )
    SEATING_CHOICES = (
...
    )
    date = models.DateField(null=True)
    name = models.CharField(max_length=35, null=True)
    phone = PhoneNumberField(null=True)   #USE THIS https://github.com/stefanfoulis/django-phonenumber-field
    email = models.EmailField(null=True)
    people = models.PositiveSmallIntegerField(choices=SEATING_CHOICES, default=None, db_index=True)
    reservation_time = models.PositiveSmallIntegerField(choices=TIME_CHOICES, default=None, db_index=True)

    def __str__(self):
        return '(%s) %s %s' % (self.date, self.name, self.phone )

1 个答案:

答案 0 :(得分:1)

clean_date条件为if的情况下,您的False方法不会返回值。您应该返回清除的数据以防万一,例如:

def clean_date(self):
    data = self.cleaned_data['date']

    # Check if a date is not in the past.
    if data < datetime.date.today():
        raise ValidationError(_('Invalid date - reservation in past'), code='invalid')
        messages.danger(request, "Reservation Created")

    # not indented under the if
    return data

否则,该函数将在数据有效的情况下返回None,在数据无效的情况下返回ValidationError