我正在尝试为我的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})
这是我想要为其发送通知的视图中的部分。
答案 0 :(得分:1)
终于找到了我的问题的答案。我刚用这段代码修改了我的js:
JS:
success: function(data) {
var dtr = $('.notification',data);
$('.notification').html(dtr);
}