我在通过以下表单清除日期时遇到问题:
class CreateArtistProfile(forms.ModelForm):
focus_str = forms.CharField()
birthdate = forms.DateField(input_formats="%d %B, %Y")
occupation = forms.CharField(required=False)
tagline = forms.CharField(required=False)
class Meta:
model=ArtistAccount
fields = ['artist_name', 'location', 'occupation', "type_label", "map_input", "tagline", "birthdate"]
我正在使用Materialise的datepicker,并尝试提交它给我的日期字符串。如果我选择日期,则字段值如下所示
2004年9月30日
但是Django继续拒绝它:
(' birthdate','输入有效日期。')
我想我已经设置了correct date formats。我做错了什么吗?在清洁过程之前是否有不同的方法来调整Django的格式预期?
答案 0 :(得分:1)
为birthdate字段添加widgets
。
birthdate 应该是models.DateField模型ArtistAccount
class CreateArtistProfile(forms.ModelForm):
focus_str = forms.CharField()
occupation = forms.CharField(required=False)
tagline = forms.CharField(required=False)
class Meta:
model=ArtistAccount
fields = ['artist_name', 'location', 'occupation', "type_label", "map_input", "tagline", "birthdate"]
widgets = {
'birthdate': forms.DateInput(format=('%d %B, %Y'), attrs={'class': 'datepicker'}),
}
答案 1 :(得分:0)
我无法弄清楚如何通过Django的表单获取自定义日期。希望有人可以发布答案,但就目前而言,这是我的解决方法:
首先,我从所需的模型字段中删除了'birthdate'并将其转换为CharField:
class CreateArtistProfile(forms.ModelForm):
focus_str = forms.CharField()
birthdate = forms.CharField()
occupation = forms.CharField(required=False)
tagline = forms.CharField(required=False)
class Meta:
model=ArtistAccount
fields = ['artist_name', 'location', 'occupation', "type_label", "map_input", "tagline"]
然后在我看来,我添加了一些额外的处理:
@require_POST
def create_artist_profile(request):
if request.method == 'POST':
form = forms.CreateArtistProfile(request.POST)
if form.is_valid():
string = request.POST["birthdate"]
birthdate = datetime.strptime(string, "%d %B, %Y")
form.instance.birthdate = birthdate
form.save()
json_obj = {"success": True}
return JsonResponse(json_obj)
else:
return JsonResponse({'success': False, 'errors': [(k, v[0]) for k, v in form.errors.items()]})