skip to Main Content

Well here I am simply trying to add follow toggle button in django template with django and jQuery ajax but I get an error

Method Not Allowed (POST): /profiles/flash/

Method Not Allowed: /profiles/flash/

I don’t get it where i am making mistake. Even I triple checked my code.

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, })

If more information is required, then tell me in a comment section. I will update my question with that information.

2

Answers


  1. Chosen as BEST ANSWER

    It worked when I update my previous code by the following code below: 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 #Change the function base view to class base view and add post function.

    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, })
    
         
    

  2. The follow method is missing the information, that it should accept POST requests. It defaults to GET.

    In your views.py import api_view and annotate follow method:

    from rest_framework.decorators import api_view 
    
    @api_view(['POST']) 
    def follow(request):
        ...
    

    More information here: https://www.django-rest-framework.org/tutorial/2-requests-and-responses/

    BTW: You don’t need to have action property in data there. The fact, that you are sending the request via POST is hint enough.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search