17

My underlying struggle is I am having trouble understanding how django templates, views, and urls are tied together... What is the simplest, bare minimum way to prompt the user to input a string, then use that string to query a database (preferably w/ python model not raw sql queries)? Should I use GET and POST methods? Should I use a form? Do I need to use a template or can I use a generic view?

when i try submitting input it just reloads the input page.

views.py:

from django.shortcuts import render
from django.shortcuts import HttpResponse
from People.models import Person

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

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

urls.py

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^People/', 'People.views.index'), 
    url(r'^People/send/', 'People.views.search'),
)

template:

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

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

Am I missing something or doing something wrong?

cezar
  • 11,616
  • 6
  • 48
  • 84
Rick James
  • 237
  • 1
  • 2
  • 8

2 Answers2

20

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.

EDIT: I have edited the code. It should work now.

views.py

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)
        try:
            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")  
    else:
        return render(request, 'form.html')

urls.py

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

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

form.html

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

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

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

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), '../templates').replace('\\','/'),
)
Archit Verma
  • 1,911
  • 5
  • 28
  • 46
  • do i need a use a template for this approach? or am i only working in the views.py and urls.py files? thanks – Rick James Jul 30 '14 at 15:41
  • If you are taking input from the user you will need to do it through form, thus you will need to use a template and then get the parameters through a `GET` or `POST` request. – Archit Verma Jul 30 '14 at 15:51
  • Really appreciate your help. people like you taking time to answer these questions really make this into a great community. i got a ways to go but im one step closer – Rick James Jul 30 '14 at 19:54
  • 1
    @RickJames I am glad I could help you. If you still have any problems you can ask it here. – Archit Verma Jul 31 '14 at 04:20
  • I have literally been looking for the entire week looking for this one StackOverflow comment... you saved my problem, here, have my babies. – stidmatt Dec 27 '19 at 22:23
3

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

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.

Alexander
  • 631
  • 1
  • 8
  • 19
  • when i hit submit, it just reloads the input page again. my first view that displays the page looks like this: `code` def index(request): return render(request, 'People/index.html') – Rick James Jul 30 '14 at 15:46