Reputation: 71
I study Django and want to use ajax. Read some examples, but have problem. I need to show all posts by click on link with name site. view:
def archive(request, page_number=1):
posts = BlogPost.objects.all()
current_page = Paginator(posts, 3)
if request.is_ajax():
t = loader.get_template("archive_ajax.html")
else:
t = loader.get_template("archive.html")
c = Context({'posts': current_page.page(page_number),
'username': auth.get_user(request).username})
return HttpResponse(t.render(c))
base.html:
<h1><a class="refresh" >mysite.example.com</a></h1> (I need click it and update posts )
<div class="content">
<div>
{% block content %}
{% endblock %}
</div>
</div>
archive.html:
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
{% include "archive_ajax.html" %}
{% endfor %}
{% endblock %}
archive_ajax.html (problem not here, I mean firstly I need to solve problem which higher ):
<h2><a href="/blog/{{post.id}}"> {{ post.title }} </a> </h2>
<p> author: {{ post.author.username }}</p>
<p> {{ post.timestamp | date:"l, F jS, Y" }} </p>
<p> {{ post.body }} </p>
In base.html includ jquery: <script src="/static/jquery-1.11.1.min.js" type="application/javascript"></script>
And I try to write code
$(document).ready(function(){
$(".refresh").click(function(){
console.log('clicked');
$(".content").load("/blog/");
});
});
when I click on link I see it on the place where might be posts:
{"content": "
\n
\u0430\u0432\u0442\u043e\u0440:
\n
\n
\n", "status": 200, "statusText": "OK"}
In command line I see "GET /blog/ HTTP/1.1" 200 151
I try another way and write:
$(document).ready(function(){
$(".refresh").click(function(){
$.ajax({
type: "GET",
url: "/blog/",
success : function(newdata) {
$('.content').html(newdata);
}
});
});
});
And now I can see nothing in place where might be posts. In command line I see "GET /blog/ HTTP/1.1" 200 151`
In view I add print
if request.is_ajax():
t = loader.get_template("archive_ajax.html")
print('it is query'`)
and in command line I see message - it's query, for ajax and js.
I use python 2.7.3, Django 1.6.5 and jquery 1.11.1.min.
Thank you all! I find my mistake, it was in ajax and in template archive_ajax.html. It's my inattention I think. In template I forgot to add loop for {{posts}}. now it's:
{% for post in posts %}
<h2><a href="/blog/{{post.id}}"> {{ post.title }} </a> </h2>
<p>автор: {{ post.author.username }}</p>
<p> {{ post.timestamp | date:"l, F jS, Y" }} </p>
<p> {{ post.body }} </p>
{% endfor %}
And in ajax I correct it:
$('.content').html(newdata.content);
Upvotes: 0
Views: 1469
Reputation: 4292
It is not a good practice to write:
<h2><a href="/blog/{{post.id}}"> {{ post.title }} </a> </h2>
Take a look at the {% url %}
template tag.
Edit - Disclaimer: the current user has not enough rate to comment. That's why this apparently answer-less answer is posted here.
Upvotes: 1