gpt4 book ai didi

python - 如果没有在 django 项目的 html 标签中分配 'action' 值,它仍然会渲染页面并将值提交到数据库,如何?

转载 作者:太空宇宙 更新时间:2023-11-03 19:58:13 24 4
gpt4 key购买 nike

urls.py

from django.contrib import admin
from django.urls import path
from poll import views

urlpatterns = [
path('', views.poll_home, name="poll_home"),
path('poll_details/<int:id>/', views.poll_details, name="poll_details"),
path('<int:id>/', views.poll, name='poll')
]

views.py

def poll(request, id=None):
if request.method == 'GET':
try:
question=Question.objects.get(id=id)
except:
raise Http404
return render(request, 'poll/poll.html',{'question':question})
if request.method == 'POST':
user_id=1
data=request.POST['choice']
ret = Answer.objects.create(user_id=user_id,choice_id = data)
if ret :
return HttpResponse('Your vote is done successfully.')
else:
return HttpResponse('Your vote is not done successfully.')
return render()

poll.html

{% extends 'employee/employee_home.html'%}

{% block content%}
<h1>Vote Page</h1>
<h3>{{ question.title}}</h3>
<form method="POST" action="">
{% csrf_token %}
{% if question%}
{% for choice in question.choices %}
<input type="radio" name="choice" value="{{ choice.id }}">
<label>{{ choice.text }}</label>
{% empty %}
<p>There is no choice available for this question</p>
{% endfor%}
<button type="submit">Vote</button>
{% else %}
<p>There is no choice available for this question</p>
{% endif%}
</form>
<h4><i>This question is created by {{question.created_by.first_name}}</i></h4>
{% endblock content%}

即使我没有在 html 页面中提及 action 值,它仍然会提交数据并成功显示结果

我想了解 django 如何知道操作路径

最佳答案

这部分造成困惑:

if request.method == 'POST':
user_id = 1
data = request.POST['choice']
ret = Answer.objects.create(user_id=user_id, choice_id=data)
if ret:
return HttpResponse('Your vote is done successfully.')
else:
return HttpResponse('Your vote is not done successfully.')
return render()

该行导致在每个 POST 请求上创建对象:Answer.objects.create(user_id=user_id, choice_id=data),并且新的对象实例将分配给 ret 变量始终为 True,这就是您收到成功消息的原因。更好的工作流程是:

if request.method == 'POST':
try:
# do not hardcode user id,
# use user instance from the request
user = request.user
choice = request.POST['choice']
ret = Answer.objects.create(user=user.id, choice_id=choice)
return HttpResponse('Your vote is done successfully.')
except Exception:
return HttpResponse('Your vote is not done successfully.')
return render()

关于python - 如果没有在 django 项目的 html 标签中分配 'action' 值,它仍然会渲染页面并将值提交到数据库,如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59426467/

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