[英]django: Take table name as input from user and show the content of the table from database
我正在嘗試在 django 中實現表單,我將從用戶那里獲取輸入,例如它的表名,然后我想在網頁上顯示所有內容。 所以,到目前為止我嘗試過下面的代碼。
視圖.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import HttpResponse
from .models import my_custom_sql
from django.core.exceptions import *
def index(request):
return render(request, 'forms_spy/form.html')
def search(request):
if request.method == 'POST':
search_id = request.POST.get('textfield', None)
try:
webpages_list = my_custom_sql.objects.get(name = search_id)
data_list = {'access_record':webpages_list}
return render(request,'forms_spy/index.html', context=data_list)
except my_custom_sql.DoesNotExist:
return HttpResponse("no such user")
else:
return render(request, 'forms_spy/form.html')
forms_spy/models.py
from django.db import models
# Create your models here.
def my_custom_sql(TABLE):
with connections["my_oracle"].cursor() as cursor:
cursor.execute("SELECT * FROM {};".format(TABLE))
row = cursor.fetchall()
return row
模板/forms_spy/form.html
<form method="POST" action="/search">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>
項目文件夾下的 urls.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from forms_spy.views import *
urlpatterns = [
# url(r'^$', views.index, name='index'),
#url(r'^', include('livefleet.urls', namespace='livefleet')),
path('admin/', admin.site.urls),
url(r'^search/', search),
url(r'^index/', index),
]
我提到了這個鏈接。 當我輸入低於錯誤的值時。
RuntimeError at /search
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/search/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
更改urls.py
從
url(r'^search/', search),
到
url(r'^search/', search, name='search'),
<form method="POST" action="{% url 'search' %}">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>
你的 url 是search/
,所以你需要在form action
輸入相同的內容
將網址更改為
path('search/', search)
動態路由的斜杠字符,例如在瀏覽器( http://domain/search
)或( http://domain/search/
)中調用(如果您同時使用它)。
模板
<form method="POST" action="/search/">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.