你好专家, 我是django的新手,并试图学习如何为MySQL数据库构建django web-framework。我可以发布我的查询(搜索词)并获得所需的结果。但我正在尝试修改我的项目,以便用户可以在提交页面中提交查询,并在执行时查看URL中的查询参数。 像这样的东西: 提交页面:http://localhost:8000/ 并且在执行页面之后将是这样的:http://localhost:8000/xtrack/?searchid=XXXX
但是现在我仍然无法在花费几天后以正确的方式弄清楚如何做到这一点。
forms.py
from django import forms
from models import Query
class SQLForm(forms.ModelForm):
xtrackid=forms.CharField(max_length=100)
def checkxID(self):
xtrackid=self.cleaned_data.get("xtrackid")
return xtrackid
class QueryForm(forms.ModelForm):
class Meta:
model=Query
fields=["xtrackid"]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from forms import SQLForm, QueryForm
import sys
def search_form(request):
return render(request, 'index.html')
def search(request):
form = QueryForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
xtrackid = form.cleaned_data.get("xtrackid")
xtrackid =xtrackid.strip()
conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "XXXX", db = "XXXtracker")
cursor = conn.cursor ()
cursor.execute ("SELECT xInfo.xtideID, xIDunID.AccessionNumber FROM xInfo, xIDunID WHERE xInfo.xtideID = xIDunID.xtideID AND xIDunID.xtideID LIKE '%" + xtrackid +"%'")
row = cursor.fetchone ()
listrow= list(row)
contextres={}
if cursor.rowcount==0:
contexterror = {
'outputerror': xtrackid
}
return render(request, 'errorform.html', contexterror)
else:
if contextres.has_key(str(listrow[0])):
contextres[str(listrow[0])].append(listrow[1])
else:
contextres[str(listrow[0])]= [listrow[1]]
resulstdict = {'contextresultinfo': contextres}
return render(request, 'resultform.html', {'xinfo': resulstdict, 'query': xtrackid})
conn.close()
else:
return HttpResponse('Please submit a valid search term.')
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from myapp import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^xtrack/$', views.search_form),
url(r'^resultform/$', views.search),
url(r'^errorform/$', views.search)
我的模板如下: 的index.html
<html>
<h1> Welcome to xTrack </h1>
<head>
<title>Search</title>
</head>
<body>
<form action="/xtrack/" method="get">
<input type="text" name="xtrackid">
<input type="submit" value="Search">
</form>
</body>
</html>
resultform.html
{% if contextresultinfo %}
<table border="1" style="width:100%">
<tr>
<td>xtide tracker ID<br> </td>
<td>Accession number<br></td>
</tr>
{% for key, values in contextresultinfo.items %}
<tr>
{% for items in values %}
<tr>
<td>{{key}}</td>
{% for data in items %}
<td>{{data}}</td>
{% endfor %}
</tr>
{% endfor %}
</tr>
{% endfor %}
</table>
{% else %}
<p>No xtrack matched your search criteria.</p>
{% endif %}
</body>
您能否告诉我在哪里需要更改项目中的代码? 感谢
答案 0 :(得分:0)
在您看来,您通过以下方式获取提交数据:
form = QueryForm(request.POST or None)
但是在你的html文件中,你将表单方法定义为:
<form action="/peptrack/" method="get">
因此request.POST
无法获取任何数据。