【发布时间】: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