Cheknov
Cheknov

Reputation: 2082

How to retrieve data in the template from a custom MariaDB connector? (Django)

I have implemented the following connector following the MariaDB documentation. Documentation

This is my db.py:

#!/usr/bin/python 
import mariadb 

conn = mariadb.connect(
    user="user",
    password="",
    host="localhost",
    database="db")
cur = conn.cursor() 
    
def get_some_data():
    cur.execute("SELECT some_id FROM `db`.some_data")
    sid = []
    for some_id in cur: 
        sid.append(some_id)
    return sid

conn.close()

So far everything is clear, what I am not clear about is...how can I show in a html select a list with the values obtained from the query to the database on my django web page?

Should I create a function in views.py and have it return something like this ?:

from db import get_some_data
def retrieve_from_db(request):
   #some code here
   return render(request, 'index.html', context)

Do I need a context?

Let's say my index.html is the following, how could I call retrieve_from_db(request) from the template and make this function call get_some_data() and display this information on the web?

index.html

    {% extends "../base.html" %}
    {% load static %}
    {% load bootstrap4 %}
    {% block content %}
    {% bootstrap_javascript %}
    //Some form to retrieve the data from the .py scripts
    <form id="retrieve_db" action="someaction?" method="post">
      <div class="form-group">
        {% someforloop? %}
        <select name="myIdList" id="myIdList">
          <option value="{{ some_id }}">{{ some_id }}</option>
        </select>
        {% endforloop %}
      </div>
    </form>
    {% endblock %}

Let's say I want the values to be displayed in the list: myIdList

I think I understand the concepts separately, but I need to know how to connect the pieces of the puzzle.

If someone can help me with a 'skeleton' of how the entire cycle could be implemented that would be of great help.

Upvotes: 0

Views: 123

Answers (1)

Charnel
Charnel

Reputation: 4432

It looks like you already moving in right direction. Put the data to the context variable and pass it to render method with request and template name.

from db import get_some_data


def retrieve_from_db(request):
   some_ids = get_some_data()
   context = {'some_ids': some_ids}
   return render(request, 'index.html', context)

And now in template iterate over your ID's:

 <div class="form-group">
     {% for some_id in some_ids %}
        <select name="myIdList" id="myIdList">
          <option value="{{ some_id }}">{{ some_id }}</option>
        </select>
     {% endfor %}
  </div>

As for calling a function from template - in case you described it doesn't seems you need that, but in general you can't call function from template, but can use template tag. Using this you'll simply pass request to it (you'll need to add it in context first) and get the result in template.

Upvotes: 2

Related Questions