我是Django的新手。我正在一个我想要接受和拒绝按钮的项目中,每当客户单击相应的按钮时,该对象就会进入接受或拒绝模板。我不知道该怎么办。
这是我的.html文件,它显示所有对象并具有接受和拒绝按钮:
<div class="body table-responsive">
<form id="form" method="POST" action = "{% url 'admin_team_detail' %}">
{% csrf_token %}
<table class="table table-hover">
<thead>
<tr>
<th>S No.</th>
<th>COMPANY NAME</th>
<th>TEAM MEMBER</th>
<th>EMAIL</th>
<th>STATUS</th>
<th><center>#</center></th>
</tr>
</thead>
<tbody>
{%for team in object%}
<tr>
<th scope="row"> {{ forloop.counter }}</th>
<td>{{team.company_name}}</td>
<td>{{team.team_member}}</td>
<td>{{team.email}}</td>
<td>-</td>
<td><center><input type="submit" value="accept" name="accept">
<input type="submit" value="reject" name="reject"></center></td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
这是views.py:
def admin_team_detail(request):
obj= Create_Team.objects.all()
print(request.method)
if request.method == 'POST':
if 'reject' in request.POST :
Create_Team.status = 'reject'
else:
Create_Team.status = 'accept'
Create_Team.save()
return render(request, "admin/team-details.html", {"object": obj})
这将呈现数据库中的所有对象并显示在网站上。
我知道我必须制作两个用于接受和拒绝的模板,但是我不知道它将如何处理具有接受或拒绝响应的对象。
我还希望如果客户端单击该按钮,那么该响应将保存在数据库中。
我还想知道是否需要在model.py中添加字段以获取状态。
答案 0 :(得分:0)
首先,您的两个按钮应该将所需的值发送到views.py
和一个隐藏的输入中,以传递团队ID
<input type="submit" value="reject" name="status">
<input type="submit" value="accept" name="status">
<input type="hidden" name="id" value={{ team.id }}>
接下来,在您的views.py
def admin_team_detail(request):
if request.method == 'POST':
# First, you should retrieve the team instance you want to update
team = Create_Team.objects.get(id=request.POST('id'))
# Next, you update the status
if request.POST.get('status'):
team.status = request.POST.get('status')
team.save()
注意:此示例假定您的团队模型具有状态字段以存储拒绝/接受值。
class Team(models.Model):
# You existing fields...
status = models.CharField(max_length=30)
答案 1 :(得分:0)
首先,您需要为模板中的每个对象创建一个表单。
{%for team in object%}
<form method="POST">
{%csrf_token%}
<input type="hidden" name="team_id" value={{ team.id }}>
<input type="submit" value="reject" name="status">
<input type="submit" value="accept" name="status">
</form>
{% endfor %}
现在,在View.py中,您需要执行以下操作:
def admin_team_detail(request):
if request.method == 'POST':
# I am assuming Create_Team is your model where all team's are present.
team = Create_Team.objects.get(id=request.POST.get("team_id"))
team.status = request.POST.get("status")
team.save()