2 回答

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
用日期時(shí)間試試這個(gè):
def clean_date(self):
date = self.cleaned_data['date']
if date < datetime.date.today():
raise ValidationError(self.error_messages['Date cannot be in the past'], code='Date cannot be in the past')
return date

TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
我設(shè)法自己解決了這個(gè)問(wèn)題。我的模型是一樣的。
forms.py
class AddMyModel(forms.ModelForm):
def clean_date(self):
date = self.cleaned_data['date']
if date < timezone.now().date():
raise forms.ValidationError(message='Date cannot be in the past')
return date
class Meta:
model = MyModel
fields = ('date')
widgets = {
'date': forms.DateInput(attrs={'type': 'date'})
}
views.py
def add(request):
if request.user.is_authenticated:
user = request.user.id
if request.method == 'POST':
form = AddMyModel(request.POST)
if form.is_valid():
date = form['date'].value()
if MyModel(user=User(pk=user), date=date):
unique_error = "User and date is already exist."
return render(request, 'mysite/add.html',
{'form': form, 'login': True, 'unique_error': unique_error})
else:
mymodel= MyModel(user=User(pk=user), date=date)
mymodel.save()
return render(request, 'mysite/successfuladd.html', {"login": True})
return render(request, 'mysite/add.html',
{'form': form, 'login': True})
form = AddMyModel()
return render(request, 'mysite/add.html', {'form': form, 'login': True})
else:
return render(request, 'mysite/homepage.html', {'login': False})
添加回答
舉報(bào)