简体   繁体   中英

Getting Data From the Request Object using Django webframework for MySQL

Hello experts, I am new in django and trying to learn how to build django web-framework for MySQL database.I can post my query (search term) and get desired results. But I am trying to modify my project so user can submit query in submission page and see their query parameter in URL when it is executed. Something like this: submission page: http://localhost:8000/ and after execution page will be like this: http://localhost:8000/xtrack/?searchid=XXXX

But still now I couldn't figure out how to do it in a right way after spending few days.

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)

]

and my templates are like: 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

Results

{% 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>

Can you please give some idea where do I need to change code in my project. Thanks

in you view, you're getting the submission data through:

form = QueryForm(request.POST or None)

but in you html file, you define your form method as:

<form action="/peptrack/" method="get">

Thus request.POST would't get any data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM