2 回答
TA贡献1871条经验 获得超8个赞
用日期时间试试这个:
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贡献1909条经验 获得超7个赞
我设法自己解决了这个问题。我的模型是一样的。
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})
添加回答
举报