django 形成日期字段
我的表单中有一个名为“生日”的字段,如下所示:
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 字段,因为日期字段对象完全不同。请告诉我如何转换,以便我可以摆脱这个问题。我把它当作一个字符串..
提前致谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 django 文档, http://docs.djangoproject.com/en /dev/ref/forms/fields/#datefield,日期字段的值标准化为 Python datetime.date 对象。
因此,如果您的模型中有类似
birthdate = models.DateField()
的内容,则可以直接从表单中分配值。但是,如果您仍想将其转换为 DateTime,假设您已将模型字段更改为 DateTime,您可以:
对于第二个选项,您需要使用以下格式创建一个 datetime.datetime 对象:
查看 日期时间 和
[time][2]
了解更多信息。As per django docs, http://docs.djangoproject.com/en/dev/ref/forms/fields/#datefield, the value of the date field normalizes to a Python datetime.date object.
So if you have something like
birthdate = models.DateField()
in your model, assigning the value from the form should be straight forward.However, if you still want to convert it into DateTime, assuming you changed your model field into DateTime already, you can either:
For the second option, you will need to create a datetime.datetime object with the following format:
Check out the python docs on datetime and
[time][2]
for more info.