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

Traceback:

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

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

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

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

File "/Users/sebastian/Developer/Zaumdo/lib/python2.7/site-packages/django/views/generic/base.py" 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'

FILES: No FILES data

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

template.html

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

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

urls.py

from django.conf.urls import patterns, url

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

urlpatterns = patterns\
(
    'discussions.views',
    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.

views.py

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

2个回答


dispatch </ code>函数中调用 handler(request,* args,** kwargs)</ code>会引发异常,因为您的视图没有 post </ code>方法: </ p>

 #django.views.generic.base.py:
def派遣(self,request,* args,** kwargs):
     #尝试调度正确的方法; 如果一个方法不存在,
     #遵循错误处理程序。 如果
     #request方法不在批准列表中。
     如果self.http_method_names中有request.method.lower():
         处理程序= 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:

# django.views.generic.base.py:
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)
    else:
        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>
     <身体>
        <!-正文标签的结尾->
        {%csrf_token%}

        <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

<html>
    <head>...</head>
    <body>
       <!--the end of the body tag -->
       {% csrf_token %}

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

Now in file js.

$(".show_answers").click(function(e) {
    e.preventDefault();
    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
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐