我的基础难题是我无法理解django模板,视图和url是如何捆绑在一起的……提示用户输入字符串,然后使用该字符串查询数据库的最简单,最简单的最小方法是什么(最好是w / python模型而不是原始sql查询)?我应该使用GET和POST方法吗?我应该使用表格吗?我需要使用模板还是可以使用通用视图?
当我尝试提交输入时,它只是重新加载了输入页面。
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'), )
模板:
<form method="POST" action="send/"> {% csrf_token %} <input type="text" name="textfield"> <button type="submit">Upload text</button> </form>
我是否缺少某些东西或做错了什么?
如果我理解正确,则希望从用户那里获取一些输入,查询数据库并根据输入显示用户结果。为此,你可以创建一个简单的django表单,该表单将接受输入。然后,你可以将参数传递给GET请求中的视图,并在数据库中查询关键字。
编辑:我已经编辑了代码。现在应该可以工作了。
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')
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>
另外,请确保将模板放置在名为的单独文件夹中templates,并将其添加到你的中settings.py:
TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), '../templates').replace('\\','/'), )