[Fixed]-Very simple user input in django


If I understand correctly, you want to take some input from the user, query the database and show the user results based on the input. For this you can create a simple django form that will take the input. Then you can pass the parameter to a view in GET request and query the database for the keyword.

I have edited the code. It should work now.


from django.shortcuts import render
from django.shortcuts import HttpResponse
from .models import Person
from django.core.exceptions import *

def index(request):
    return render(request, 'form.html')

def search(request):
    if request.method == 'POST':
        search_id = request.POST.get('textfield', None)
            user = Person.objects.get(name = search_id)
            #do something with user
            html = ("<H1>%s</H1>", user)
            return HttpResponse(html)
        except Person.DoesNotExist:
            return HttpResponse("no such user")  
        return render(request, 'form.html')


from django.conf.urls import patterns, include, url
from People.views import *

urlpatterns = patterns('',
    url(r'^search/', search),
    url(r'^index/', index)


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

<button type="submit">Upload text</button>

Also make sure that you place your templates in a seperate folder named templates and add this in your settings.py:

    os.path.join(os.path.dirname(__file__), '../templates').replace('\\','/'),


For a user input you’ll need 2 views – one to display the page with the form and another to process the data. You hook the first view to one url, say “feedback/”, and the other one to a url like “feedback/send/”. You also need to specify this second url in your form tag.

<form method="POST" action="feedback/send/">
    <input type="text" name="textfield">
    <button type="submit">Upload text</button>

Now in the second view you can obtain the form data and do whatever you want with it.

def second_view(request):
    if request.method == "POST":
        get_text = request.POST["textfield"]
        # Do whatever you want with the data

Take a look at this page Fun with Forms. It’ll give you the basic understanding. I would also advice to work through the whole book.
You should use ether GET or POST (GET is probably not secure). Using form is not mandatory, as you can style it and perform all the validation yourself and then pass the data straight to the model.

Leave a comment