我有一个表单,允许用户在个人资料中更新自己的生日。我希望它只有在用户年满18岁时才有效。以下是我尝试过的:
型号.py
class Profile(models.Model):
birthday = models.DateField()
forms.py
from django import forms
from datetime import datetime
from .models import Profile
class ProfileUpdateForm(forms.ModelForm):
birthday = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))
def clean_birthday(self):
dob = self.cleaned_data['birthday']
age = (datetime.now() - dob).days / 365
if age < 18:
raise forms.ValidationError('You must be at least 18 years old')
return dob
class Meta:
model = Profile
fields = ('birthday',)
提交后,我得到了TypeErrorunsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'
这是我的观点:
@login_required
def update_my_profile_view(request):
profile = Profile.objects.get(user=request.user)
form = ProfileUpdateForm(request.POST or None, instance=profile)
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect('users:my_profile')
有人能解释一下我做错了什么吗?
问题就在这一行:age = (datetime.now() - dob).days / 365
datetime.now()
->返回一个datetime
dob
->是date
因此,您要减去两种不同的数据类型!
from datetime import date
date.today()
这将只返回日期,您可以使用它来代替datetime.now((