我的表单中有一个名为birthdate的字段,如:
class Personal_info_updateForm(forms.Form):
birthdate = forms.DateField(widget=SelectDateWidget(years=[y for y in range(1930,2050)]))
..
..
views.py
def personal_info(request):
mc = MenuCategories()
listCategories = mc.getCategories()
oe = OEConnector()
if request.method == 'POST':
f1 = Personal_info_updateForm(request.POST)
print request.POST
if f1.is_valid():
first_name = f1.cleaned_data['first_name']
last_name = f1.cleaned_data['last_name']
c=[last_name,first_name]
name = " ".join(c)
print name
birthdate = f1.cleaned_data['birthdate']
birthdate_year,birthdate_month,birthdate_day=['','','']
birthdate = [birthdate_year,birthdate_month,birthdate_day]
c=" ".join(birthdate)
print birthdate
title = f1.cleaned_data['title']
print title
email = f1.cleaned_data['email']
mobile = f1.cleaned_data['mobile']
phone = f1.cleaned_data['phone']
result = update_details(name,first_name,last_name,birthdate,email,mobile,phone)
print result
return HttpResponse('/Info?info="Congratulations, you have successfully updated the information with aLOTof"')
a1.html我打电话给整个表格,如
<form action="" method="POST">
<table style="color:black;text-align:left; margin-left: 20px;">
{{ form.as_table }}
</table>
<input type="submit" value="UPDATE">
</form>
我想在Postgresql中存储我的生日值。但它没有工作,所以我研究了我需要将它转换为DateTime字段,因为日期字段对象是完全不同的..请告诉我如何转换,以便我可以摆脱这个问题。我把它作为一个字符串..
提前致谢
答案 0 :(得分:1)
根据django docs http://docs.djangoproject.com/en/dev/ref/forms/fields/#datefield,date字段的值规范化为Python datetime.date对象。
因此,如果您的模型中有birthdate = models.DateField()
之类的内容,则应该直接从表单中指定值。
#views.py
birthdate = f1.cleaned_data['birthdate']
my_model_instance.birthdate = birthdate
但是,如果您仍想将其转换为DateTime,假设您已将模型字段更改为DateTime,则可以:
对于第二个选项,您需要使用以下格式创建datetime.datetime对象:
import datetime
bday = datetime.datetime(year, month, day)
查看datetime和[time][2]
上的python文档以获取更多信息。