0

Is it possible to take a query from a database that will grab all values from a given vaule i.e query = Table.objects.filter(x=y) send it to HTML like so:

<table>
    <tr>
        <th>Value 1</th>
        <th>Value 2</th>
        <th>Value 3</th>
    </tr>
    {% for value in query %}
    <tr>
        <td>{{ value.val1 }}</td>
        <td>{{ value.val2 }}</td>
        <td>{{ value.val2 }}</td>
    </tr>
    {% endfor %}
</table>

Lets say the query returns 3 objects. That means the table will have 3 rows of data but in HTML all the <td> tags are the same. How can I identify each <td> per row so that I can manipulate the data and save it back to the database?

I have tried with jquery, but I am only able to manipulate the first row.

GreenSaber
  • 1,118
  • 2
  • 26
  • 53
  • With JS (native or jQuery or ...) you can create new DOM Elements. Give your Table an Id and try to create `tr`s and `td`s in loop. After that, append them to your Table. See: https://www.w3schools.com/jquery/jquery_dom_add.asp – Chris May 30 '17 at 13:54

1 Answers1

1

using context in the views.py file?

def MySite(...):
   articles = Table.objects.filter(x=y)
   context = {
     "articles": articles,
   }
   return render(request, "my_site/mything.html", context)

in template:

{% for x in articles %}
{{x}}
{%endfor%}

For the changing data part use Ajax/Api (take a look at the documentation) . You need to set up an API View which gets triggered by an Ajax call (on click or whatever). This is changing the Database, but there is a lot to take care of. If you do it right your site does not even reload and all the data are saved.

For triggering the right value you have to give them classes or an ID (remember that IDs are unique). You can also set up an For Loop Counter and work with that.

hope that helps.

hansTheFranz
  • 2,511
  • 4
  • 19
  • 35
  • Thanks for the answer! This is getting me on the right track. Now if I use `{{ forloop.counter }}` is there a way in jquery or ajax that I can grab an entire row of data based on the `` tag that has the counter? – GreenSaber May 30 '17 at 14:16
  • 1
    One small note. If it's a public project you want to make sure that the user changing these objects have the rights to do so, otherwise I could change the id of the elements using the inspector and break arbitrary db entries. – Jonas Grumann May 30 '17 at 14:26
  • @Evan I never used in that context so I can't help you here but those two look promising ;) [link]https://stackoverflow.com/questions/376081/how-to-get-a-table-cell-value-using-jquery [link]https://stackoverflow.com/questions/9437914/how-to-select-this-specific-td-element-and-its-text-with-jquery @ Jonas you are completely right. Thanks for mentioning it – hansTheFranz May 30 '17 at 14:48