Django: Выполнение пользовательского SQL напрямую и отображение на странице

Теперь работает.

views.py

from django.http import HttpResponse
from django.db import connection

def query():
    with connection.cursor() as cursor:
        cursor.execute('SELECT some, stuff FROM here;')
        row = cursor.fetchall()

    return row


def index(request):
    return HttpResponse(query())

Я сделал это вот так...

/opt/my_project/my_app/templates/my_app/generate_html.html

<html>
<h1>Generate HTML</h1>

<form method="POST" action="">
    {% csrf_token %}
    {{ form }}
    <button type="submit">Submit Query</button>
</form>

</html>

/opt/my_project/my_project/settings.py

'DIRS': ['/opt/my_project/my_app/templates/my_app'],

/opt/my_project/my_app/urls.py

path('generate_html/', generate_html, name = "generate_html"),

/opt/my_project/my_app/forms.py

from django import forms

class InputForm(forms.Form):
   email = forms.EmailField(max_length = 100)

/opt/my_project/my_app/views.py

def query(email):
    with connection.cursor() as cursor:
        query = '''SELECT some, stuff
                FROM here
                WHERE email = %s
                ORDER BY stuff;
                '''
        values = (email,)
        cursor.execute(query, values)
        select = cursor.fetchall()

    return select


def generate_html(request):
    if request.method == 'POST':
        email = request.POST.get('email', None)
        try:
            html = '<!DOCTYPE html><html><body>' 

            for row in query(email):
                some, stuff = row
                html += 'Row: ' + some + ' ' + stuff + '<br>' 

            html += '<br><br>' + '<a href = "/my_app/generate_html/">Search Again!</a>' + '</body></html>'
            return HttpResponse(html)
        except Exception as e:
            return HttpResponse(str(e))
    else:
        context ={}
        context['form']= InputForm()
        return render(request, "generate_html.html", context)
Вернуться на верх