【发布时间】:2017-11-27 14:28:10
【问题描述】:
我有 2 个查询集:发布和评论。我正在使用 django-el-pagination 使用 ajax 来呈现这些。
这是我的看法:
def profile(request, user, extra_context=None):
profile = Profile.objects.get(user__username=user)
page_template = 'profile.html'
if request.is_ajax():
user_queryset = request.GET.get('user_queryset')
print('Queryset:', user_queryset)
if user_queryset == 'user_posts':
page_template = 'user_posts.html'
elif user_queryset == 'user_comments':
page_template = 'user_comments.html'
else:
pass
print('Template:', page_template)
user_posts = Post.objects.filter(user=profile.user).order_by('-date')
user_comments = Comment.objects.filter(user=profile.user).order_by('-timestamp')
context = {'user_posts': user_posts,'user_comments': user_comments, 'page_template': page_template}
if extra_context is not None:
context.update(extra_context)
return render(request, page_template, context)
我有一个 ajax 调用来找出正在使用的查询集。因此,当单击“更多 cmets”或“更多帖子”(在模板中)以获取更多分页对象时,我知道它来自哪个查询集。
但是,当我使用上面的代码并单击 ajax 分页的“更多”时,它会附加整个页面,而不是相关的子模板(user_posts.html 或user_comments.html)。但if request.is_ajax() 代码块工作正常;它打印使用正确的模板,所以这不应该发生。
当我将该代码块更改为此
if request.is_ajax():
page_template = 'user_posts.html'
Post 的 ajax 分页有效。但是我也想为Comment 添加ajax 分页。为什么我的初始 if request.is_ajax() 不起作用,我该如何解决?
编辑:
点击more posts时的输出:
Queryset: None
Template: profile.html
Queryset: user_posts
Template: user_posts.html
js
$('body').on('click', '.endless_more', function() {
console.log($(this).html()); #works successfully
var user_queryset;
if ($(this).html() === 'more posts') {
console.log('POSTS'); #works successfully
var user_queryset = 'user_posts'
} else if ($(this).html() === 'more user comments') {
user_queryset = 'user_comments';
console.log('COMMENTS'); #works successfully
} else {
console.log('none');
}
$.ajax({
type: 'GET',
url: window.location.href,
data: {
'user_queryset': user_queryset
}
})
});
profile.html
<!--posts-->
<div class="user_posts_div">
<div class="endless_page_template">
{% include "user_posts.html" %}
</div>
</div>
<!--comments-->
<div class="user_comments_div">
<div class="endless_page_template">
{% include "user_comments.html" %}
</div>
</div>
user_posts.html(子模板)
{% paginate 5 user_posts %}
{% for post in user_posts %}
<div class="user_post">
<p class="user_post_title_p"><a class="user_post_title" href="{% url 'article' category=post.entered_category id=post.id %}">{{ post.title }}</a></p>
<p class="user_post_category">/{{ post.entered_category }}</p>
<p class="user_post_date">{{ post.date|timesince }}</p>
</div>
{% endfor %}
{% show_more 'more posts' '...' %}
【问题讨论】:
标签: jquery python ajax django pagination