0

I am trying to implement form in django, where I will take input from user, e.g, its table name and then I want to show all the content on the webpage. So, far I tried below code.

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

templates/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 under project folder:

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),
]

I referred to this link. When I entered the value getting below error.

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.
LOrD_ARaGOrN
  • 3,884
  • 3
  • 27
  • 49

2 Answers2

2

change in urls.py

from

url(r'^search/', search),

to

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>

ur url is search/ , so u need to put the same in the form action

Exprator
  • 26,992
  • 6
  • 47
  • 59
0

change urls to

path('search/', search)

slash character for dynamic route, example call in browser (http://domain/search) or (http://domain/search/) if you using both it's work.

templates

<form method="POST" action="/search/">
{% csrf_token %}
<input type="text" name="textfield">

<button type="submit">Upload text</button>
</form>
harmain
  • 188
  • 1
  • 9