Django Ajax jQuery URL

I have the following template file, where I am going to perform an ajax request. If I click on the show link in the template the jquery function gets executed and then I receive the following error message in the developer console of my browser:

  • TypeError at /projects/djangobook/discussions/5/show/8

  • 'NoneType' object is not callable


File "/Users/sebastian/Developer/Zaumdo/lib/python2.7/site-packages/django/core/handlers/" in get_response 115. response = callback(request, *callback_args, **callback_kwargs)

File "/Users/sebastian/Developer/Zaumdo/lib/python2.7/site-packages/django/views/generic/" in view 68. return self.dispatch(request, *args, **kwargs)

File "/Users/sebastian/Developer/Zaumdo/lib/python2.7/site-packages/braces/" in dispatch 107. request, *args, **kwargs)

File "/Users/sebastian/Developer/Zaumdo/Zaumdo/core/" in dispatch 49. return super(GroupAwareMixin, self).dispatch(request, *args, **kwargs)

File "/Users/sebastian/Developer/Zaumdo/lib/python2.7/site-packages/django/views/generic/" in dispatch 86. return handler(request, *args, **kwargs)

Exception Type: TypeError at /projects/djangobook/discussions/5/show/8

Exception Value: 'NoneType' object is not callable

Request information: GET: No GET data

POST: name = u'sebastian'


COOKIES: csrftoken = 'fWD0OojhrpTLhuxtxb2NF96rVSnKGpWy' sessionid = 'fccuv36b538pqnulqyhbdsq7ihyrvjo5'


{% for post in object_list %}
    {{ post.creator }}
    {{ post.created }}
    {{ post.body }}
    <a href="{% groupurl post_answer group %}">Answer</a>
    <a class="show_answers" href="{% groupurl post_show_answers group %}">Show</a>
{% endfor %}

<script type="text/javascript">
    $(".show_answers").click(function(e) {
        var self = $(this);
        ajax_req = $.ajax({
            url: self.attr("href"),
            type: "POST",
            data: {name: "sebastian"},
            success: function(ctx) {console.log(ctx);}

from django.conf.urls import patterns, url

from discussions.views import DiscussionListView, DiscussionCreateView, DiscussionUpdateView,
DiscussionDeleteView, PostListView, PostCreateView, PostAnswerView

urlpatterns = patterns\
    url(r'^$', DiscussionListView.as_view(), name='discussion_list'),
    url(r'^create/$', DiscussionCreateView.as_view(), name='discussion_create'),
    url(r'^update/(?P<pk>\d+)$', DiscussionUpdateView.as_view(), name='discussion_update'),
    url(r'^delete/(?P<pk>\d+)$', DiscussionDeleteView.as_view(), name='discussion_delete'),
    url(r'^(?P<discussion_id>\d+)/$', PostListView.as_view(), name='discussion'),
    url(r'^(?P<pk>\d+)/create/$', PostCreateView.as_view(), name='post_create'),
    url(r'^(?P<discussion_id>\d+)/answer/(?P<pk>\d+)', PostAnswerView.as_view(), name='post_answer'),
    url(r'^(?P<discussion_id>\d+)/show/(?P<post_id>\d+)', PostListView.as_view(), name='post_show_answers'),

In this view I would like to send an HttpResponse.

class PostListView(LoginRequiredMixin, GroupAwareMixin, ListView):
    model = Post
    template_name = 'discussions/discussion.html'

    discussion = None
    post = None
    posts = None

    def get_queryset(self):
        # Get the discussions from the pk in the url
        self.discussion = get_object_or_404(Discussion, pk=self.kwargs['discussion_id'])

        # return HttpResponse(json.dumps("success"), mimetype="application/json")

        # Fetch all the root posts (depth=1) in the discussion
        self.posts = self.discussion.posts.filter(depth=depth)
        return self.posts

    def get_context_data(self, **kwargs):
        context = super(PostListView, self).get_context_data(**kwargs)
        context['discussion'] = self.discussion
        return context


dispatch </ code>函数中调用 handler(request,* args,** kwargs)</ code>会引发异常,因为您的视图没有 post </ code>方法: </ p>
def派遣(self,request,* args,** kwargs):
     #尝试调度正确的方法; 如果一个方法不存在,
     #遵循错误处理程序。 如果
         处理程序= getattr(self,request.method.lower(),self.http_method_not_allowed)
         处理程序= self.http_method_not_allowed
     返回处理程序(请求,* args,** kwargs)
</ code> </ pre>

您的Ajax发布网址与页面网址相同:</ p>

  ajax_req = $ .ajax({
         网址:self.attr(“ href”),
</ code> </ pre>

因此,您应该在视图类中添加 post </ code>方法。</ p>
     </ div>



Exception throws on calling handler(request, *args, **kwargs) in dispatch function because your view didnt have post method:

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

Your ajax post url is same as page url:

    ajax_req = $.ajax({
        url: self.attr("href"),

So, you should add post method to your view class.

Django必须使用ajax发送请求才能生成令牌,如文档 csrf_token 。</ p>

我使用以下令牌开发应用程序。</ p>

在layout.html </ p>中

     ... </ head>

        <br>             $ tagToken = $(“ {{%csrf_token%}”));<br>             var CSRF_TOKEN = $ tagToken.find(“ input [name =&#39;csrfmiddlewaretoken&#39;]”)。val();<br>         &lt;/ script&gt;<br>      &lt;/ body&gt;<br> &lt;/ html&gt;<br> &lt;/ code&gt; &lt;/ pre&gt;</p> <p><p>现在在文件js中。&lt;/ p&gt;</p> <p><pre> <code> $(“。show_answers”)。click(function(e){<br>      e.preventDefault();<br>      var self = $(this);<br>      ajax_req = $ .ajax({<br>          网址:self.attr(“ href”),<br>          输入:“ POST”,<br>          数据:{名称:“塞巴斯蒂安”},<br>          beforeSend:function(xhr,settings){<br>              如果(!(/ ^ http:。* /。test(settings.url)|| /^https:.*/.test(settings.url))){<br>                  xhr.setRequestHeader(“ X-CSRFToken”,CSRF_TOKEN);<br>              }<br>          },<br>          成功:function(ctx){console.log(ctx);}<br>      });<br> });<br> &lt;/ code&gt; &lt;/ pre&gt;</p> <p><p>这就是您接受django请求的全部。&lt;/ p&gt;<br>      &lt;/ div&gt;</p>



Django to send a request using ajax is necessary to generate a token as explained in the documentation csrf_token.

I develop my applications in this token as follows.

In layout.html

       <!--the end of the body tag -->
       {% csrf_token %}

       <script type="text/javascript">
           $tagToken = $("{% csrf_token %}");
           var CSRF_TOKEN = $tagToken.find("input[name='csrfmiddlewaretoken']").val();

Now in file js.

$(".show_answers").click(function(e) {
    var self = $(this);
    ajax_req = $.ajax({
        url: self.attr("href"),
        type: "POST",
        data: {name: "sebastian"},
        beforeSend: function(xhr, settings) {
            if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                xhr.setRequestHeader("X-CSRFToken", CSRF_TOKEN);
        success: function(ctx) {console.log(ctx);}

That would be all for you to accept the request django.

Csdn user default icon