gpt4 book ai didi

Django/HTTP - 使用 POST 请求发送查询字符串 - 不推荐吗?

转载 作者:可可西里 更新时间:2023-11-01 16:56:13 25 4
gpt4 key购买 nike

这是我的模型.py:

class Blog(models.Model):
user = models.ForeignKey(User)
votes = models.IntegerField(default=0)

class BlogExtended(models.Model):
blog = models.ForeignKey(Blog)
usersVoted = models.ManyToManyField(User)

基本上,每个博客都有一个创建该博客的用户。如果用户喜欢某人的博客,他们可以投票给它。每当博客获得投票时,“投票”计数器就会加一。在我的模板中,我不希望投票按钮是一个只显示“投票”的按钮。我希望投票按钮是一个图像。因为一旦用户单击投票按钮,我将更改数据库(将“投票”字段增加一个)我需要使用 POST 请求。所以这就是我最初的模板(我最初使用 GET 请求):

{% if Blogs %} <!-- Blogs is a list of blogs -->
<ul class="blogs">
{% for blog in Blogs %}
<li>
<a href="/vote/?id={{ blog.id }}" class="vote"><img src="images/voteButton.jpg" </a>

这是我处理/vote/url 的 View :

def voteView(request):
if request.GET.has_key('id'): #if it is a GET request which has the blogs id
try:
id = request.GET['id']
blog = Blog.objects.get(id=id) #if the Blog is found
blog.votes += 1 #make a change to the 'votes' field in the DB
blog.blogextended_set.usersVoted.add(request.user) #make a change in the 'usersVoted' field in the DB
blog.save()

但如您所见,我使用的是 GET 而不是 POST。我意识到我需要使用 POST,因为我正在更改数据库,所以我尝试将其设为 POST 请求:

<form method="post" action="/vote/">{% csrf_token %}
<button type="submit">
<img src="images/voteButton.jpg" alt="vote" />
<!-- I used button rather than input because with button, I was able to replace the button with an image.. I was unable to replace the button with an image -->
</button>
</form>

这个表单基本上不向/vote/发送任何信息(它只发送当前用户对象:request.user)。我还需要发送博客的 ID。通过在 GET 请求的 URL 中添加查询字符串,我能够以初始方式发送 ID。我能想到的在我的 POST 请求中添加博客 ID 的唯一方法是在 URL 中添加一个查询字符串,所以我的表单会像这样操作:

<form method="post" action="/vote/?id={{ blog.id }}">

我意识到用 POST 请求发送查询字符串是我以前从未见过/做过的事情。如果我发送带有 POST 请求的查询字符串可以吗,还是不推荐?使用 POST 请求发送查询字符串会出现什么问题?

其他帮助:如果不推荐,任何人都可以建议另一种发送附加信息以及 POST 请求的方法吗?

最佳答案

您只需要在表单中添加另一个字段:

<input type="hidden" name="blog_id" value="{{ blog.id }}" />

完整形式:

<form method="post" action="/vote/">{% csrf_token %}
<button type="submit">
<img src="images/voteButton.jpg" alt="vote" />
</button>
<input type="hidden" name="blog_id" value="{{ blog.id }}" />
</form>

那么,你的 View 应该是这样的:

def voteView(request):
if request.POST.has_key('blog_id'):
try:
id = request.POST['blog_id']
...

关于Django/HTTP - 使用 POST 请求发送查询字符串 - 不推荐吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24337640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com