[英]Passing Values in POST Method
I am trying to pass the value or a variable using JS to my Django BackEnd.我正在尝试使用 JS 将值或变量传递给我的 Django 后端。
When click on a Like Button, I am getting the ID of the post and a variable called Iliked saying "yes" or "no" depending if the user already liked the clicked post or not.当点击一个 Like 按钮时,我得到了帖子的 ID 和一个名为 Iliked 的变量,它说“是”或“否”,这取决于用户是否已经喜欢点击的帖子。
When I click on Like on Post 77 with my user Bar, I then get in console log:当我使用我的用户 Bar 在 Post 77 上单击 Like 时,我会进入控制台日志:
Since my API allows to pass the ID within its URL, all I care about is to pass the Iliked value in order to have my Views.py update the DB accordingly:由于我的 API 允许在其 URL 中传递 ID,因此我只关心传递 Iliked 值,以便让我的 Views.py 相应地更新数据库:
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('#likebtn').forEach(item => {
item.addEventListener('click', () => {
const id = item.getAttribute('data-id');
const Iliked = item.getAttribute('data-Iliked');
like(id, Iliked);
});
});
})
function like(id, Iliked) {
console.log (id)
console.log (Iliked)
fetch(`/like/${id}`, {
method: 'POST',
credentials: 'same-origin',
headers:{
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify({
Iliked:'Iliked'
})
})
.then(response => {return response.json()})
.then(data => {
console.log (data)
})
return false;
}
@login_required
@csrf_exempt
def like(request, id):
if request.method == "POST":
CurrentUser = request.user.id
Iliked = json.load(request)['Iliked'] #Get data from POST request
print("This is the JSON Iliked received from the front end : ", Iliked)
if Iliked == 'no':
Liker = User.objects.get(user=CurrentUser)
ThePostToLike = Post.objects.get(id=id)
ThePostToLike.like.add(Liker)
ThePostToLike.save()
Iliked == 'yes'
print("The like is now ADDED")
elif Iliked == 'yes':
Liker = User.objects.get(user=CurrentUser)
ThePostToLike = Post.objects.get(id=id)
ThePostToLike.like.remove(Liker)
ThePostToLike.save()
Iliked == 'no'
print("The like is now REMOVED")
databack = {
'Iliked': Iliked,
}
return JsonResponse(databack, safe=False)
The problem that I have here is that I am loosing the value (yes/no) of Iliked when using JSON.stringify().我在这里遇到的问题是,在使用 JSON.stringify() 时,我失去了 Iliked 的值(是/否)。
When I load "Iliked" in the backend, its value is "Iliked" instead of yes/no.当我在后端加载“Iliked”时,它的值为“Iliked”而不是“是/否”。
This in turns totally bypass my DB logic and returns "Object { Iliked: "Iliked" }" back to the front end.这反过来完全绕过了我的数据库逻辑并将“Object { Iliked:“Iliked”}”返回到前端。
Hope you can help !希望你能帮忙!
EDIT:编辑:
Models楷模
class User(AbstractUser):
pass
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
post = models.CharField(max_length=350, null=True, blank=True)
like = models.ManyToManyField("User", blank=True, related_name="like_amount")
With the '' removed as per @DeepSpace, my logic now works.根据@DeepSpace 删除'',我的逻辑现在可以工作了。
However, I am hit by:但是,我受到以下打击:
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'user' into field. Choices are: date_joined, email, first_name, follower_name, following_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, like_amount, logentry, password, post, profile, user_permissions, username
[21/Feb/2021 16:23:18] "POST /like/77 HTTP/1.1" 500 18572
When I load "Iliked" in the backend, its value is "Iliked" instead of yes/no.当我在后端加载“Iliked”时,它的值为“Iliked”而不是“是/否”。
Because that's what you set it to:因为这就是您将其设置为:
body: JSON.stringify({
Iliked: 'Iliked'
})
Remove the ''
so it is not a string, but the value of the variable:删除''
所以它不是字符串,而是变量的值:
body: JSON.stringify({
Iliked: Iliked
})
Then you can use the JS shortcut:然后就可以使用JS快捷方式了:
body: JSON.stringify({ Iliked })
{ Iliked }
creates an object, with a single key-value pair where the key is 'Iliked'
and the value is the value of the variable Iliked
. { Iliked }
创建一个 object,其中键为'Iliked'
,值是变量Iliked
的值。
As suggested, I was passing a literal string instead of a var:正如建议的那样,我传递的是文字字符串而不是 var:
BAD (Iliked passed as string)坏(我喜欢作为字符串传递)
body: JSON.stringify({
Iliked:'Iliked'
})
GOOD (Iliked passed as a variable)好(我喜欢作为变量传递)
body: JSON.stringify({
Iliked:Iliked
})
For the second question, I was trying to get Liker = User.objects.get(user=CurrentUser)
while user expects a string.对于第二个问题,我试图获取Liker = User.objects.get(user=CurrentUser)
而用户需要一个字符串。 Changing it to id did the trick: Liker = User.objects.get(id=CurrentUser)
将其更改为 id 就可以了: Liker = User.objects.get(id=CurrentUser)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.