django:以表名作为用户输入,显示数据库表的内-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

django:以表名作为用户输入,显示数据库表的内

kun坤 2019-12-25 21:39:48 40

我尝试在django中实现form,我将从用户e处获取输入。g,它的表名然后我想展示网页上的所有内容。所以,到目前为止,我尝试了以下代码。 views.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>

项目文件夹下的url .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.

问题来源StackOverflow 地址:/questions/59387206/django-take-table-name-as-input-from-user-and-show-the-content-of-the-table-fro

数据库 Python
分享到
取消 提交回答
全部回答(1)
  • kun坤
    2019-12-25 21:39:55

    改变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>
    

    你的网址是搜索/,所以你需要把相同的形式行动

    0 0
数据库
使用钉钉扫一扫加入圈子
+ 订阅

分享数据库前沿,解构实战干货,推动数据库技术变革

推荐文章
相似问题