(django) strftime 格式不能正常工作,不同的时区,顺序
(django) strftime format does not work properly, different timezone, order
这是关于公告的评论。当有人写评论推送'submit'时,ajax发送数据给views.py的pushComment(),保存数据,return给ajax。这样用户就可以在不刷新页面的情况下看到评论。
问题是数据格式。
我使用了 strftime(format),但它存在一些问题。
TIMEZONE 未应用于新评论。我的服务器 TIMEZONE 是 'asia/seoul' 但新评论显示 TIMEZONE 为 UTC。 (只针对新评论)
格式顺序已更改。我的格式是 'date to time' 但时间比日期更早。
这是我的代码。
views.py
def pushComment(request):
pk = request.POST.get('writing_id', 1)
ac = ArticleComments(
user = User.objects.get(username=request.user.username),
article = FreeBoards.objects.get(id=pk),
comments = request.POST.get('comments', 'Nothing'),
# target = 0,
pub_date = datetime.now().replace(microsecond=0),
like = 0,
)
ac.save()
com_cnt = ArticleComments.objects.filter(article=pk).count()
FreeBoards.objects.filter(id=pk).update(comments = com_cnt)
user = MyUser.objects.get(nickname=request.user.myuser)
data = {
'writing_id': pk,
'user': user.nickname,
'comments': ac.comments,
# 'target': ac.target,
'pub_date': str(ac.pub_date.strftime('%y-%m-%d %H:%M:%S %Z')), # why TIMEZONE is UTC ?????
'like': ac.like,
'com_cnt': com_cnt,
}
return HttpResponse(simplejson.dumps(data), content_type="application/json")
模板
<form role="form" class="form-inline" id="form-com-id" name="commentform" onsubmit="return false;" action="." method="POST">{% csrf_token %}
<div class="form-group">
<div class="col-xs-11">
<input type="text" class="form-control" id="id-comment" name="comname" placeholder="Leave your comment.">
</div>
</div>
<div class="form-group">
<div class="col-xs-1">
<button type="submit" class="btn btn-default" id="btn-comment-submit" OnClick="javascript:commentCheck();">Submit</button>
</div>
</div>
</form>
<br><br>
<div class="comments-group">
<div id="com-start" class="panel-heading">자유로운 댓글</div>
{% if comment_list %}
{% for c in comment_list %}
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="{% cycle 'box1' 'box2' 'box3' 'box4' 'box5' %}">
<div class="boxbox">
<div class="com-user">
<p>작성자: {{c.user.myuser}}
<button onclick=deleteCom()>×</button>
</p>
</div>
<div class="com-content ellipsis">
<p>{{c.comments}}</p>
</div>
<div class="com-date"
<p>{{c.pub_date}}</p>
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}
</div>
javascript
$('#form-com-id').submit(function() {
var com = $('#id-comment').val();
if(com){
$.ajax({
url : "/sle/freeboards/pushComment/",
type : "POST",
data : {
writing_id : '{{writing_id}}',
comments : com,
csrfmiddlewaretoken: '{{csrf_token}}',
},
dataType : "json",
success:function(data){
$('#id-comment').val('');
/* create elements and class matching */
var divcomgrp = document.getElementsByClassName('comments-group');
var divgrid = document.createElement("div");
divgrid.className = 'col-xs-12 col-sm-6 col-md-4';
var divbox = document.createElement('div');
if(data.com_cnt % 5 == 0) {
divbox.className = 'box5';
} else if (data.com_cnt % 5 == 1) {
divbox.className = 'box1';
} else if (data.com_cnt % 5 == 2) {
divbox.className = 'box2';
} else if (data.com_cnt % 5 == 3) {
divbox.className = 'box3';
} else if (data.com_cnt % 5 == 4) {
divbox.className = 'box4';
}
// quotient = data.com_cnt / 5;
var divcontainer = document.createElement("div");
divcontainer.className = 'boxbox';
var divuser = document.createElement("div");
divuser.className = 'com-user';
var divcont = document.createElement("div");
divcont.className = 'com-content';
var divdate = document.createElement("div");
divdate.className = 'com-date';
/* create paragraphs */
var puser = document.createElement('p');
var textnode = document.createTextNode(data.user);
puser.appendChild(textnode);
var butdel = document.createElement('button');
butdel.innerHTML = '×';
butdel.onclick = deleteCom;
puser.appendChild(butdel);
var pcomments = document.createElement('p');
var textnode2 = document.createTextNode(data.comments);
pcomments.appendChild(textnode2);
var pdate = document.createElement('p');
var textnode3 = document.createTextNode(data.pub_date);
pdate.appendChild(textnode3);
/* appending children */
divuser.appendChild(puser);
divcont.appendChild(pcomments);
divdate.appendChild(pdate);
divcontainer.appendChild(divuser);
divcontainer.appendChild(divcont);
divcontainer.appendChild(divdate);
divbox.appendChild(divcontainer);
divgrid.appendChild(divbox);
divcomgrp[0].appendChild(divgrid);
},
failure: function(data){
alert('fail!!');
},
});
}
});
settings.py
TIME_ZONE = 'Asia/Seoul'
结果
无法上传图片...所以我来写吧
来自comments.html的原始日期格式:2015年2月25日,11:31 a.m
ajax 评论(新评论临时):UTC 02:31:53 15-02-25
(两条评论都写在11:31,我写了一条评论刷新了,然后马上又加一条评论。)
(如果我刷新页面,第二个消失,所有日期格式打印为第一个。)
不知道为什么我输入的格式不行
p.s)
...还有一个,我应该怎么做才能没有时间打印 'datetimefield'?
需要数据库的 DateTimeField 但在某个页面中我只想显示日期,而不是时间。
创建新的 ArticleComments
实例时,您需要将时区感知日期时间设置为 pub_date
。
from django.utils import timezone
ac = ArticleComments.objects.create(
...
pub_date = timezone.now().replace(microsecond=0),
...
)
其次,如果我错了,请纠正我,但我认为您应该先将 ac. pub_date
转换为本地时间,然后再将其格式化为字符串:
from django.utils import timezone
data = {
...
'pub_date': timezone.localtime(ac.pub_date).strftime('%y-%m-%d %H:%M:%S %Z')),
...
}
关于在没有时间的情况下将 datetime
对象转换为 date
的最后一个问题,您可以在该日期时间调用 .date()
方法。
>>> from django.utils.timezone import now
>>> today_as_date = now().date()
>>> today_as_date_str = today_as_date.strftime('%Y-%m-%d')
有关详细信息,您可能想查看 timezone documentation in Django and pytz 库。
这是关于公告的评论。当有人写评论推送'submit'时,ajax发送数据给views.py的pushComment(),保存数据,return给ajax。这样用户就可以在不刷新页面的情况下看到评论。
问题是数据格式。
我使用了 strftime(format),但它存在一些问题。
TIMEZONE 未应用于新评论。我的服务器 TIMEZONE 是 'asia/seoul' 但新评论显示 TIMEZONE 为 UTC。 (只针对新评论)
格式顺序已更改。我的格式是 'date to time' 但时间比日期更早。
这是我的代码。
views.py
def pushComment(request):
pk = request.POST.get('writing_id', 1)
ac = ArticleComments(
user = User.objects.get(username=request.user.username),
article = FreeBoards.objects.get(id=pk),
comments = request.POST.get('comments', 'Nothing'),
# target = 0,
pub_date = datetime.now().replace(microsecond=0),
like = 0,
)
ac.save()
com_cnt = ArticleComments.objects.filter(article=pk).count()
FreeBoards.objects.filter(id=pk).update(comments = com_cnt)
user = MyUser.objects.get(nickname=request.user.myuser)
data = {
'writing_id': pk,
'user': user.nickname,
'comments': ac.comments,
# 'target': ac.target,
'pub_date': str(ac.pub_date.strftime('%y-%m-%d %H:%M:%S %Z')), # why TIMEZONE is UTC ?????
'like': ac.like,
'com_cnt': com_cnt,
}
return HttpResponse(simplejson.dumps(data), content_type="application/json")
模板
<form role="form" class="form-inline" id="form-com-id" name="commentform" onsubmit="return false;" action="." method="POST">{% csrf_token %}
<div class="form-group">
<div class="col-xs-11">
<input type="text" class="form-control" id="id-comment" name="comname" placeholder="Leave your comment.">
</div>
</div>
<div class="form-group">
<div class="col-xs-1">
<button type="submit" class="btn btn-default" id="btn-comment-submit" OnClick="javascript:commentCheck();">Submit</button>
</div>
</div>
</form>
<br><br>
<div class="comments-group">
<div id="com-start" class="panel-heading">자유로운 댓글</div>
{% if comment_list %}
{% for c in comment_list %}
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="{% cycle 'box1' 'box2' 'box3' 'box4' 'box5' %}">
<div class="boxbox">
<div class="com-user">
<p>작성자: {{c.user.myuser}}
<button onclick=deleteCom()>×</button>
</p>
</div>
<div class="com-content ellipsis">
<p>{{c.comments}}</p>
</div>
<div class="com-date"
<p>{{c.pub_date}}</p>
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}
</div>
javascript
$('#form-com-id').submit(function() {
var com = $('#id-comment').val();
if(com){
$.ajax({
url : "/sle/freeboards/pushComment/",
type : "POST",
data : {
writing_id : '{{writing_id}}',
comments : com,
csrfmiddlewaretoken: '{{csrf_token}}',
},
dataType : "json",
success:function(data){
$('#id-comment').val('');
/* create elements and class matching */
var divcomgrp = document.getElementsByClassName('comments-group');
var divgrid = document.createElement("div");
divgrid.className = 'col-xs-12 col-sm-6 col-md-4';
var divbox = document.createElement('div');
if(data.com_cnt % 5 == 0) {
divbox.className = 'box5';
} else if (data.com_cnt % 5 == 1) {
divbox.className = 'box1';
} else if (data.com_cnt % 5 == 2) {
divbox.className = 'box2';
} else if (data.com_cnt % 5 == 3) {
divbox.className = 'box3';
} else if (data.com_cnt % 5 == 4) {
divbox.className = 'box4';
}
// quotient = data.com_cnt / 5;
var divcontainer = document.createElement("div");
divcontainer.className = 'boxbox';
var divuser = document.createElement("div");
divuser.className = 'com-user';
var divcont = document.createElement("div");
divcont.className = 'com-content';
var divdate = document.createElement("div");
divdate.className = 'com-date';
/* create paragraphs */
var puser = document.createElement('p');
var textnode = document.createTextNode(data.user);
puser.appendChild(textnode);
var butdel = document.createElement('button');
butdel.innerHTML = '×';
butdel.onclick = deleteCom;
puser.appendChild(butdel);
var pcomments = document.createElement('p');
var textnode2 = document.createTextNode(data.comments);
pcomments.appendChild(textnode2);
var pdate = document.createElement('p');
var textnode3 = document.createTextNode(data.pub_date);
pdate.appendChild(textnode3);
/* appending children */
divuser.appendChild(puser);
divcont.appendChild(pcomments);
divdate.appendChild(pdate);
divcontainer.appendChild(divuser);
divcontainer.appendChild(divcont);
divcontainer.appendChild(divdate);
divbox.appendChild(divcontainer);
divgrid.appendChild(divbox);
divcomgrp[0].appendChild(divgrid);
},
failure: function(data){
alert('fail!!');
},
});
}
});
settings.py
TIME_ZONE = 'Asia/Seoul'
结果
无法上传图片...所以我来写吧
来自comments.html的原始日期格式:2015年2月25日,11:31 a.m
ajax 评论(新评论临时):UTC 02:31:53 15-02-25
(两条评论都写在11:31,我写了一条评论刷新了,然后马上又加一条评论。)
(如果我刷新页面,第二个消失,所有日期格式打印为第一个。)
不知道为什么我输入的格式不行
p.s) ...还有一个,我应该怎么做才能没有时间打印 'datetimefield'? 需要数据库的 DateTimeField 但在某个页面中我只想显示日期,而不是时间。
创建新的 ArticleComments
实例时,您需要将时区感知日期时间设置为 pub_date
。
from django.utils import timezone
ac = ArticleComments.objects.create(
...
pub_date = timezone.now().replace(microsecond=0),
...
)
其次,如果我错了,请纠正我,但我认为您应该先将 ac. pub_date
转换为本地时间,然后再将其格式化为字符串:
from django.utils import timezone
data = {
...
'pub_date': timezone.localtime(ac.pub_date).strftime('%y-%m-%d %H:%M:%S %Z')),
...
}
关于在没有时间的情况下将 datetime
对象转换为 date
的最后一个问题,您可以在该日期时间调用 .date()
方法。
>>> from django.utils.timezone import now
>>> today_as_date = now().date()
>>> today_as_date_str = today_as_date.strftime('%Y-%m-%d')
有关详细信息,您可能想查看 timezone documentation in Django and pytz 库。