我正在尝试为我的 django 应用程序创建通知,我必须在模板的div 中显示数据库中的更改。我希望 ajax 定期访问我的数据库,如果有任何更改,那么它们应该显示在该div 中。我希望我的数据来自 3 个不同的模型,并且其中任何一个的任何更改都应在我的模板的div 中通知。
我该怎么做?
模板:
<div class="notification">
{% for like in likes_notify %}
{% if like.item.reward != None %}
<div class="like_newsfeed">
<a href="/employee/{{ emp_code }}/social-info/single-news-feed/{{ like.item.reward.pk }}/show/"> {{ like.user.get_full_name }} liked your post : {{ like.item.reward }} </a>
</div>
{% else %}
<div class="like_news_post">{{ like.item.comment.pk }}
<a href="/employee/{{ emp_code }}/social-info/single-news-feed/{{ like.item.comment.pk }}/show/"> {{ like.user.get_full_name }} liked your comment "{{ like.item.comment }}". </a>
</div>
{% endif %}
{% endfor %}
<br><hr>
{% for comment in comments_notify %}
{% if comment.item.reward != None %}
<div class="comment_newsfeed">
<a href="/employee/{{ emp_code }}/social-info/single-news-feed/{{ comment.item.reward.pk }}/show/"> {{ comment.user.get_full_name }} commented on your post : {{ comment.item.reward }} with "{{ comment }}". </a>
</div>
{% else %}
<div class="comment_news_post">{{ comment }}
<a href="/employee/{{ emp_code }}/social-info/single-news-feed/{{ comment.item.reward.pk }}/show/"> {{ comment.user.get_full_name }} commented on your post "{{ comment }}". </a>
</div>
{% endif %}
{% endfor %}
<br><hr>
{% for reward in rewards_notify %}
<div class="reward_newsfeed">
<a href="/employee/{{ emp_code }}/social-info/single-news-feed/{{ reward.pk }}/show/"> {{reward.role_history.organisation_role.user.get_full_name }} got a reward : {{ reward }} </a>
</div>
{% endfor %}
</div>
.JS:
function worker(){
var url = '/employee/'+get_emp_code()+'/home/dashboard/';
// $(".notification").load(url + ' .notification',data, function () { setTimeout(worker, 5000); });
$.ajax({
type:'get',
url: url,
success: function(data) {
// $('.notification').load(url + " .notification", data);
// $('.notification').load(url + " .notification").html(data);
$('.notification').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 3000);
}
});
}
$(document).ready(function(){
setTimeout(worker, 5000);
});
我试过写这个js,但这加载了我的整个页面两次,而不是div。我实际上已将基本模板扩展到此模板中,因此它也在我的div 中加载整个基本模板的数据。
视图:
def get_context(request,*args,**kwargs):
context = {}
likes = Like.objects.exclude(user = request.user).order_by('-date_edited')[:2]
comments = Comment.objects.filter(user = request.user).order_by('-last_updated')[:2]
rewards = Reward.objects.filter(role_history__organisation_role__organisation=request.user.organisation_user.organisation, approved=True).order_by('-last_updated')[:2]
#notification = chain(likes,comments,rewards)
context.update({'likes_notify':likes,'comments_notify':comments,
'rewards_notify':rewards})
这是我视图中要为其发出通知的部分。
终于找到了我问题的答案。我刚刚用这段代码修改了我的js:
.JS:
success: function(data) {
var dtr = $('.notification',data);
$('.notification').html(dtr);
}