繁体   English   中英

如何将数据从 JavaScript 文件发送到 views.py django?

[英]How to send data from JavaScript file to views.py django?

如何将数据(本示例中的 user_to_follow)发送到我的 views.py function(关注)以进行一些更新?

我正在尝试从我的 JavaScript 发送用户名,然后将登录的用户名添加到该用户名列表中(全部在我的 views.py function 中完成)

视图.py。

def follow(request, profile_to_follow):
    try:
        user_to_follow = User.objects.get(username=profile_to_follow)
        user_to_following = Profile.objects.get(user=request.user.id)
    except User.DoesNotExist:
        return JsonResponse({"error": "Profile not found."}, status=404)
    if request.method == "PUT":
        user_to_following.following.add(user_to_follow)
        return HttpResponse(status=204)

index.js

function follow_user(user_to_follow){
    // How To send the user_to_follow to my views.py method.
    // to add the current logged in user to the user_to_follow following list
    console.log(user_to_follow)
}

网址.py

from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),

    # API Routes
    path("posts", views.compose_post, name="compose_post"),
    path("posts/all_posts", views.show_posts, name="show_posts"),
    path("posts/<int:post_id>", views.post, name="post"),
    path("profile/<str:profile>", views.display_profile, name="profile"),
    path("<str:profile_posts>/posts", views.display_profile_posts, name="profile_posts"),
    path("follow/<str:user_to_follow>", views.follow, name="follow"),
]

最简单的方法是使用 Ajax 查询将数据从模板发送到您的 views.py

index.js

<script>
   $(document).ready(function() {
     function follow_user(user_to_follow){
     $.ajax({
         type: "PUT",
         url: "{% url 'follow' user_to_follow %}",
         data: {
                user_data: user_to_follow,
                csrfmiddlewaretoken: '{{ csrf_token }}'
                },
         success: function( data )
         {
         alert("Successful Added User to list");
         }
     });
     });
 });
</script>

视图.py

def follow(request, profile_to_follow):
    try:
        user_to_follow = User.objects.get(username=profile_to_follow)
        user_to_following = Profile.objects.get(user=request.user.id)
    except User.DoesNotExist:
        return JsonResponse({"error": "Profile not found."}, status=404)
    if request.method == "PUT" and request.is_ajax():
        user_to_following.following.add(user_to_follow)
        return HttpResponse(status=204)

request.is_ajax()

这将根据请求是否为 AJAX 调用返回 boolean 值。

也可以参考这个文档https://api.jquery.com/jQuery.ajax/#options

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM