【问题标题】:How to make a seperate view function for AJAX requests?如何为 AJAX 请求制作单独的视图功能?
【发布时间】:2017-06-08 17:01:38
【问题描述】:

我的视图函数变得相当混乱,那么是否可以从视图文件中的单独函数调用我的 ajax 请求?

这是我的观点

def article(request, category, id):

    name = resolve(request.path).kwargs['category']
    for a, b in CATEGORY_CHOICES:
        if b == name:
            name = a
            instance = get_object_or_404(Post, id=id, category=name)

    allauth_login = LoginForm(request.POST or None)
    allauth_signup = SignupForm(request.POST or None)

    #comments
    comment = CommentForm(request.POST or None)
    ajax_comment = request.POST.get('text')
    comment_length = len(str(ajax_comment))

    comment_list = Comment.objects.filter(destination=id)
    score = CommentScore.objects.filter(comment=comment_list)

    if request.is_ajax():
        username_clicked = request.GET.get('username_clicked')
        profile = Profile.objects.get(username=username_clicked)
        if username_clicked:
            print(profile.age)
        if comment.is_valid():
            comment = Comment.objects.create(comment_text=ajax_comment, author=str(request.user), destination=id)
            comment.save()

            score = CommentScore.objects.create(comment=comment)
            score.save()
            username = str(request.user)
            return JsonResponse({'text': ajax_comment, 'text_length': comment_length, 'username': username})
        else:
            print(comment.errors)


    context = {
        'score': score,
        'comment_list': comment_list,
        'comment': comment,
        'instance': instance,
        'allauth_login': allauth_login,
        'allauth_signup': allauth_signup
    }

    return render(request, 'article.html', context)

例如,对于username_clicked,我想将其取出并在同一个视图文件中使其成为类似这样的函数:

def raise_profile(request):
    if request.is_ajax():
        username_clicked = request.GET.get('username_clicked')
        profile = Profile.objects.get(username=username_clicked)
        if username_clicked:
            print(profile.age)
            return HttpResponse()

这可能吗?请记住,这些都在同一个 URL url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article')

这可能吗?

更新功能:

def raise_profile(request):
    if request.is_ajax():
        username_clicked = request.GET.get('username_clicked')
        profile = Profile.objects.get(username=username_clicked)
        if username_clicked:
            print(profile.age)
            response_data = json.dumps({username_clicked})
            return HttpResponse(response_data, content_type='application/json')

【问题讨论】:

    标签: jquery python ajax django django-views


    【解决方案1】:

    是的,这是可能的。

    只需在 urls.py 中为 AJAX 函数提供它自己的 URL,并在发布数据时指向该 URL。

    urls.py:

    url(r'^custom-ajax-function/', 'module.views.raise_profile'), 
    

    你可以像这样返回:

        response_data = json.dumps({})
        return HttpResponse(response_data, content_type='application/json')
    

    如有必要,将所有数据打包到 json 转储中。

    另外,我不确定流行的观点是什么,但我会确保您正在使用 django 清理您的请求数据。我不确定您的 Django 版本是否这样做,但我一直使用表单来清理 GET/POST 数据。我相信获取原始 GET 数据可能容易被注入。

    编辑: 我相信 OP 和我对如何发布数据有不同的策略。我通过按钮处理程序上的 jquery 调用处理我所有的 AJAX 帖子。所以,在你的 HTML 中,我会在 jquery 中做这样的事情:

    $('.button_handler').on('click', function(){ 
      //logic
      var posted_username = '...'
      .ajax({
          url: "/custom-ajax-function/",
          type: "POST",
          data: { 
               username: 'posted_username,
              },
          success:function(data) { 
             //Do something if it works, if you want
         }
    });
    

    这将允许您将数据直接从网页直接发布到 django 函数的 url。如果您在发送数据时遇到问题,很可能您需要启用CSRF Protection,但这就像将一些javascript 设置函数粘贴到您的页面中一样简单。

    另外,这只是我,也许你的 Django 版本不同,但我 像这样编写我的处理程序:

    class data_form(forms.Form)
        username = form.CharField() 
    
    def raise_profile(request):
        username_clicked = None 
        if request.method == 'POST':
            form = data_form(request.POST, request.FILES)
            if form.is_valid():
                username_clicked = form.cleaned_data.get('username')
        response_data = json.dumps(username_clicked)
        return HttpResponse(response_data, content_type='application/json')
    

    is_valid() 确保您的 POST 数据中没有非法字符或注入脚本。

    【讨论】:

    • 好的,所以我的模板指向这样的网址:<h3><a href="{% url 'raise_profile' %}" class="username">{{ i.author }}</a></h3>url(r'^raise_profile/', views.raise_profile, name='raise_profile'),但我收到一条错误消息:raise_profile didn't return an HttpResponse object. It returned None instead. 你知道为什么吗?我将在我的编辑中发布该功能。
    • 我认为您只是在做与我不同的事情,尽管我犹豫说哪个版本是“正确的”。但是我的版本应该可以为你解决这个问题。我希望我的编辑对您有所帮助。
    • 谢谢,我设法让它在做一些与你的非常相似的事情stackoverflow.com/questions/41820487/…
    猜你喜欢
    • 2021-09-18
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 2019-01-27
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    相关资源
    最近更新 更多