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
It worked when I update my previous code by the following code below: html
ajax :
views.py #Change the function base view to class base view and add post function.
The
follow
method is missing the information, that it should acceptPOST
requests. It defaults toGET
.In your
views.py
import api_view
and annotatefollow
method:More information here: https://www.django-rest-framework.org/tutorial/2-requests-and-responses/
BTW: You don’t need to have
action
property indata
there. The fact, that you are sending the request viaPOST
is hint enough.