Django:从SQL查询生成HTML页面



可以,但是…

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

如果我想从管理员那里获得一个限制为用户或组的过滤响应,该怎么办?

例如,如果用户在BAIT组中,他们可以过滤WHERE电子邮件LIKE 'bob@bait.com';

我是这样做的…

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

最新更新