django how to Pass an id from a template to a view

Viewed 39

I want to update an item and I have this 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')

when I clicked an item, the data goes to my def update then run this postgres function

let's say I have this list of items

test001 | update

test002 | update

here's my template

<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>

if this is not possible then maybe someone can recommend an alternative solution

1 Answers

if u want to update something do this:

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

In your template:

<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>

Add this inside url:

path('update/<int:id>',views.update)  

By doing this, you can update anything. hope it will solve your problem

Related