我正在尝试通过POST请求将一个320个字符的文本帖子发送到/路由。在那条路线上,我有一个类似于Twitter的社交网站,用于发布帖子和关注用户。要创建和编写帖子,我希望它是异步的,我的意思是,我希望用户编写一个帖子,当他按下按钮将其发布时,不应重新加载页面。
这是我的html文件:
<div class="container">
<h1>All Posts</h1>
<div class="row">
<div class="span12 well">
<form method="post">
{% csrf_token %}
<textarea class="span11" id="new_message" name="new_message"
placeholder="Write something nice" rows="5"></textarea>
<h6 id="characters">320 characters remaining</h6>
<button class="btn btn-info" type="submit">Post New Message</button>
</form>
</div>
</div>
</div>
这是我要在JavaScript中尝试做的事情,但我得到了403:
document.querySelector("form").onsubmit = () => {
//sending values by POST method
fetch('/', {
method: 'POST',
body: JSON.stringify({
content: document.querySelector('#new_message').value,
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
})
event.preventDefault()
}
});
我也不太确定这是否是正确的方法。
后端:
def index(request):
if request.method == "POST":
content = request.POST["new_message"]
print(request.user)
print(content)
return render(request, "network/index.html")
#post = Posts(user=request.user, content=content)
return render(request, "network/index.html")
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "network/login.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "network/login.html")
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse("index"))
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, "network/register.html", {
"message": "Passwords must match."
})
# Attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, "network/register.html", {
"message": "Username already taken."
})
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "network/register.html")
答案 0 :(得分:0)
因为403表示禁止,所以我将尝试检查您尝试调用的实体的权限。确保正确的文件具有正确级别的执行权限。通过您使用的apache或其他类型的Web服务器检查错误日志,访问日志可能会在其中找到某些内容。另外,在您的JS中,您正在向控制台记录一些内容,JS将什么推送到控制台?