如何添加条件以在Django中有效

时间:2019-01-09 04:41:56

标签: django python-3.x django-forms django-views

简介:我正在创建一个事件应用,我希望用户选择从今天起3天到今天最多30天之间的日期

class CreateEvent(IsVerifiedMixin, CreateView):
    model = Event
    form_class = EventForm
    template_name = 'event/event_form.html'

    def form_valid(self, form, *args, **kwargs):
        self.object = form.save(commit=False)
        event = self.object
        today = datetime.date.today()
        user = self.request.user
        if today + datetime.timedelta(days=3) <= event.date <= today + datetime.timedelta(days=30):    
            event.user = self.request.user
            event.initial_stock = event.stock
            slug = self.kwargs['slug']                    
            event.save()                
        else: #I know the below line of code is wrong. How do I fix this
            messages.error(self.request, "The event date has to be equal or more than 3 days away and less than 30 days")    
        return super().form_valid(form)

如果日期正确,则以上内容为我提供了IntegrityError,如果日期正确,则创建对象。我只想获取一个表单错误,并且表单不转到下一页

以下是此表单。py

class EventForm(forms.ModelForm):
    price = forms.DecimalField(decimal_places=2, max_digits=5)
    stock = forms.IntegerField()

    class Meta:
        model = Event
        fields = ('price', 'stock', 'date', 'time_from', 'time_to', 'lat', 'lon')

2 个答案:

答案 0 :(得分:0)

这是一个简单的解决方法https://docs.djangoproject.com/en/1.11/ref/forms/api/#django.forms.Form.add_error

if today + datetime.timedelta(days=3) <= event.date <= today + datetime.timedelta(days=30):
    ...
    return super().form_valid(form)

else:
    form.add_error(field="date", error="The date has to be more than or equal to 3 days and less than 30 days")
    return super().form_invalid(form)

答案 1 :(得分:0)

向您的ModelForm添加清理函数:

def clean(self):
    time_from = self.cleaned_data.get('time_from')
    time_to = self.cleaned_data.get('time_to')
    if #implement your logic:
        raise forms.ValidationError("Validation msg")
    return self.cleaned_data