从事Django项目。我正在尝试像Instagram一样实现follow按钮。当我按下follow按钮并更新后端的followers计数时,我正在尝试发送fetch请求。然后获取更新计数的响应,并更新页面上的innerHtml。但我得到了以下错误。 如果有人能帮我,那就太好了
index.js:13 Fetch failed loading: POST "http://127.0.0.1:8000/follow". It is showing error below in fetch code
failed to load resource: the server responded with a status of 500 (Internal Server Error)
这是我的密码:
网址
path("follow", views.follow, name="follow"),
模型
class User(AbstractUser):
followersCount = models.IntegerField(blank=True)
followingCount = models.IntegerField(blank=True)
def __str__(self):
return f"{self.username}"
class FollowList(models.Model):
userName = models.CharField(max_length=64)
followersList = models.ManyToManyField(User, blank=True, related_name="followers")
followingList = models.ManyToManyField(User, blank=True, related_name="following")
视图:
@csrf_exempt
@login_required
def follow(request):
# Composing a new email must be via POST
if request.method != "POST":
return JsonResponse({"error": "POST request required."}, status=400)
# get data
user = request.user
currentUser = user.username
a = User.objects.get(username = currentUser)
data = json.loads(request.body)
user_name = data.get("username")
b = User.objects.get(username= user_name)
status = data.get("status")
try:
a1 = FollowList.objects.get(username=currentUser)
b1 = FollowList.objects.get(username=user_name)
except FollowList.DoesNotExist:
a1 = FollowList(username=currentUser)
b1 = FollowList(username=user_name)
a1.save()
b1.save()
if status == "Follow":
a1.followingList.add(b)
b1.followersList.add(a)
a1.save()
b1.save()
countA = a.followingCount
countA = countA + 1
a.followingCount = countA
countB = b.followersCount
countB = countB + 1
b.followersCount = countB
a.save()
b.save()
else:
a1.followingList.remove(b)
b1.followersList.remove(a)
a1.save()
b1.save()
countA = a.followingCount
countA = countA - 1
a.followingCount = countA
countB = b.followersCount
countB = countB - 1
b.followersCount = countB
a.save()
b.save()
bUser = User.objects.get(username = user_name)
newFollowers = bUser.followersCount
return JsonResponse({"newFollowersCount": f"{newFollowers}"}, status=201)
javaScript:
const btn = document.querySelector("#followUnfollow");
const user = document.querySelector("#username");
const followers = document.querySelector("#followers");
const follow_unfollow = btn.value;
document.getElementById("followUnfollow").onclick = function(){
if (btn.value == "Follow"){
document.getElementById("followUnfollow").value = "Unfollow";
}else{
document.getElementById("followUnfollow").value = "Follow";
}
console.log(user.innerHTML);
console.log(follow_unfollow);
fetch("/follow", {
method: "POST",
body: JSON.stringify({
username: user.innerHTML,
status: follow_unfollow,
}),
})
.then(response => response.json())
.then(result => {
console.log(result);
const newFollowers = result.newFollowersCount;
followers.innerHTML = `${newFollowers}`;
});
};
});
目前没有回答
相关问题 更多 >
编程相关推荐