【问题标题】:Method Not Allowed (POST): /profiles/flash/ Method Not Allowed: /profiles/flash/不允许的方法 (POST):/profiles/flash/ 不允许的方法:/profiles/flash/
【发布时间】:2021-02-09 04:58:48
【问题描述】:

这里我只是想用 django 和 jQuery ajax 在 django 模板中添加跟随切换按钮,但我得到一个错误

不允许的方法 (POST):/profiles/flash/

不允许的方法:/profiles/flash/

我不明白我犯错的地方。甚至我还检查了我的代码。

html

<form method='post'>
          <button class="btn {% if is_following %}btn-warning{% else %}btn-primary{% endif %}" id="like-button" toggle="{{user.userprofile}}">{% csrf_token %}
           {% if is_following %}Unfollow {% else %}Follow{% endif %}
          </button>
        </div>
        </form>

jquery,ajax

<script>
   var user = $('#test').attr('user');
   console.log(user,'test purpose');
  $(document).on('click', '#follow-button', function (e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: '{% url "profiles:follow" %}',
      data: {
        user_toggle: user,
        csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
        action: 'post'
      },
      success: function (json) {
        document.getElementById("is_following").innerHTML = json['is_following']
      },
      error: function (xhr, errmsg, err) {
      }
    });
  })
</script>

urls.py

app_name = 'profiles'

urlpatterns = [ path('<str:username>/',UserProfileDetailView.as_view(),name = 'detail'),
    path('follow/',follow,name = 'follow'),
]

views.py

def follow(request):
     if request.POST.get('action') == 'post':
        result = ''
        profile_ = UserProfile.objects.get(user__username__iexact=request.user.username)
        is_following = False
        username_to_toggle=request.POST.get('user_toggle')
        follower = profile_.follower.filter(username__iexact=username_to_toggle).first()
        if follower:
            profile_.follower.remove(follower.id)
        else:
            new_follower = User.objects.get(username__iexact=username_to_toggle)
            profile_.follower.add(new_follower.id)
            is_following = True
        return JsonResponse({'is_following': is_following, })

如果需要更多信息,请在评论部分告诉我。我会用这些信息更新我的问题。

【问题讨论】:

  • 因此该消息来自您的服务器,不允许您发布到该路径。尝试使用 curl(或邮递员)首先检查您的 api(如:没有 ajax 的东西)此外,您的服务器的其余部分是什么?似乎它并没有以您认为的方式暴露端点。您可能想要添加一个 MWE,以便我们可以重现。
  • 好吧,我没有为此使用rest api。我只是从 django/http 文件中导入 jsonresponse 类。
  • 好的,让我试着澄清一下,当错误发生时。你渲染一些按钮,这行得通,对吧?然后你点击那个按钮,它会向你的 python 后端发送一个 POST 请求,对吧?在响应中你得到一个 405 对吗? MWE 会有所帮助。
  • Flash实际上是用户的用户名
  • 我添加了views.py,其中follow函数与该url链接

标签: jquery django ajax django-views django-templates


【解决方案1】:

follow 方法缺少应该接受 POST 请求的信息。默认为GET

在您的views.py import api_view 并注解follow 方法:

from rest_framework.decorators import api_view 

@api_view(['POST']) 
def follow(request):
    ...

更多信息在这里:https://www.django-rest-framework.org/tutorial/2-requests-and-responses/

顺便说一句:您不需要在data 中拥有action 属性。事实上,您通过POST 发送请求就足够了。

【讨论】:

【解决方案2】:

当我通过以下代码更新以前的代码时,它起作用了: html

          <button class="btn {% if is_following %}btn-warning{% else %}btn-primary{% endif %}" id="follow-button" toggle="{{user.userprofile}}">{% csrf_token %} #Change the id name
           {% if is_following %}Unfollow {% else %}Follow{% endif %}
          </button>
        </div>

ajax:

<srcipt>
 $(document).on('click', '#follow-button', function (e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: '{% url "profiles:toggle" %}',
      data: {
        user_toggle: user,
        csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
        action: 'POST',
      },
      success: function (json) {
        document.getElementById("is_following").innerHTML = json['result']
      },
      error: function (xhr, errmsg, err) {
      }
    });
  })
</script>

views.py #将函数基视图改为类基视图并添加post函数。

class UserProfileFollowToggle(LoginRequiredMixin,View):
    login_url = '/accounts/login/'
    def post(self, request):
            username_to_toggle = request.POST.get("user_toggle")
            profile_, is_following = UserProfile.objects.toggle_follow(request.user, request.user.id ,username_to_toggle)
def toggle_follow(self, request_user,user_id, username_to_toggle):
        profile_ = UserProfile.objects.get(user__username__iexact=request_user.username)
        is_following = False
        follower = profile_.follower.filter(username__iexact=username_to_toggle).first()
        if follower:
            profile_.follower.remove(follower.id)
        else:
            new_follower = User.objects.get(username__iexact=username_to_toggle)
            profile_.follower.add(new_follower.id)
            is_following = True
            return JsonResponse({'result': is_following, })

     

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2020-06-18
    • 2017-09-17
    • 2020-06-17
    • 2014-05-23
    • 2021-07-07
    相关资源
    最近更新 更多