Django как передать id из шаблона в представление
Я хочу обновить элемент и у меня есть этот views.py
def update(request,cl_itemid):
if request.method == "POST":
cursor = connection.cursor()
resolve_item = get_object_or_404(Clearanceinsert, pk=cl_itemid)
cursor.execute("select resolve_clearance_item('"+resolve_item+"')")
return render(request, 'clearance/index.html')
else:
return render(request, 'clearance/index.html')
когда я нажимаю на элемент, данные попадают в мой def update затем запускается эта функция postgres
Допустим, у меня есть список элементов
test001 | update
test002 | update
вот мой шаблон
<table style="width:100%">
<tr>
<th>cl_itemid</th>
<th colspan="2">Actions:</th>
</tr>
{%for data in data%}
<tr>
<td>{{data.cl_itemid}}</td>
<td><a href="{% url 'update' data.cl_itemid %}">Update</a></td>
</tr>
{%endfor%}
</table>
если это невозможно, то, возможно, кто-то может порекомендовать альтернативное решение
если вы хотите обновить что-то, сделайте следующее:
def update(request, id):
machine = Model.objects.get(id=id) #Add here your model name
form = Form(request.POST,instance=machine) #Add here form name
if form.is_valid():
form.save()
return HttpResponseRedirect('/') #Add your path, where you want to go after update
return render(request,'edit.html',{'machine': machine}) #Add here your context
В вашем шаблоне:
<form method="post" class="post-form" action="/appaname/update/{{ machine.id }}"> #Add here context name
<table style="width:100%">
<tr>
<th>cl_itemid</th>
<th colspan="2">Actions:</th>
</tr>
<tr>
<td>{{data.cl_itemid}}</td> #Add here context name.id
<td><button type="submit" class="btn btn-success btn-lg">Update</button></td>
</tr>
</table>
</form>
Добавьте это внутрь url:
path('update/<int:id>',views.update)
Сделав это, вы сможете обновить все, что угодно. надеюсь, это решит вашу проблему