我一直在通过Django练习完成探戈工作,以将自己的牙齿切成Django。差不多完成了,但是Ajax part有问题。
用于自动添加页面的Ajax函数未被调用。知道问题是什么,因为其他函数正在被调用。
在shell提示符下,根本没有调用ajax函数。需要帮助。
随附相关代码。与上面的网站链接相同。
静态/rango-ajax.js
$('.rango-add').click(function(){
var catid = $(this).attr("data-catid");
var title = $(this).atrr("data-title");
var url = $(this).attr("data-url");
$.get('/rango/auto_add_page/', {category_id: catid, url: url, title: title}, function(data){
$('#pages').html(data);
me.hide();
});
});
templates / rango / category.html
{% if user.is_authenticated %}
<button data-catid="{{category.id}}" data-title="{{ result.title }}" data-url="{{ result.link }}" class="rango-add btn btn-mini btn-info" type="button">Add</button>
{% endif %}
rango / views.py
@login_required
def auto_add_page(request):
context = RequestContext(request)
cat_id = None
url = None
title = None
context_dict = {}
if request.method == 'GET':
cat_id = request.GET['category_id']
url = request.GET['url']
title = request.GET['title']
if cat_id:
category = Category.objects.get(id=int(cat_id))
p = Page.objects.get_or_create(category=category, title=title, url=url)
pages = Page.objects.filter(category=category).order_by('-views')
#Adds our results list to the template context under name pages.
context_dict['pages'] = pages
return render_to_response('rango/page_list.html', context_dict, context)
rango / urls.py
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^goto/$', views.track_url, name='track_url'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^auto_add_page/$', views.auto_add_page, name='auto_add_page'),
完整的代码位于此link。
最佳答案
您的代码是好的,唯一要做的就是在/tango/templates/rango/page_list.html中定义模板。该模板具有以下代码:
{% if pages %}
<ul>
{% for page in pages %}
<li>
<a href="{% url 'goto' %}?page_id={{page.id}}"> {{ page.title}}</a>
{% if page.views > 1 %}
({{page.views}} views)
{% elif page.views == 1 %}
({{page.views}} view)
{% endif %}
</li>
{% endfor %}
</ul>
{% else %}
<strong> No Pages currently in category. </strong>
{% endif %}
在类别模板中,您必须定义以下代码:
% if category %}
{% if user.is_authenticated %}
<a href="/rango/category/{{ category_name_url }}/add_page/"> Add a new Page</a> <br>
{% endif %}
{% if pages %}
<div id="pages">
<ul>
{% for page in pages %}
<li>
<a href="{% url 'goto' %}?page_id={{page.id}}"> {{ page.title}}</a>
{% if page.views > 1 %}
({{page.views}} views)
{% elif page.views == 1 %}
({{page.views}} view)
{% endif %}
</li>
{% endfor %}
</ul>
</div>
{% else %}
<strong> No Pages currently in category. </strong>
{% endif %}
{% else %}
The specified category {{ category_name }} does not exist!
{% endif %}