我的潜在困难是我无法理解
django模板,视图和网址是如何绑在一起的…提示用户输入字符串的最简单,最简单的方法是什么,然后使用该字符串查询数据库(最好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')
urls.py
from django.conf.urls import patterns,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('\\','/'),)