Very simple user input in django

后端 未结 2 1498
一生所求
一生所求 2020-12-05 21:03

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 u

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 21:19

    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 = ("

    %s

    ", 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

    {% csrf_token %}

    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('\\','/'),
    )
    

提交回复
热议问题