2014-03-13 53 views
0

我是新來的django需要幫助,試圖用(Django == 1.4)構建庫存工具,這將很容易獲取列表主機/服務器從數據庫(MySQL)Django + MySQL,form /創建mysql查詢,將有效參數傳遞給url

我想要實現的是簡單地提供主機名作爲參數與URL並將其提取到Django應用程序,構建查詢並顯示在UI上的結果。

實例網址:http://test.example.com/gethost/?hostname=localhost

== urls.py:

urlpatterns = patterns('', 
    # Examples: 
    url(r'^gethost', 'dc.views.gethost', name='gethost'), 

== views.py:

def gethost(request, hostname, template_file="gethost.html"): 
    from django.db import connection, transaction 
    hostname = request.GET.get('hostname') 
    cursor = connection.cursor() 
    cursor.execute("SELECT * FROM inventory WHERE hosts='%s'" % 'hostname') 
    rows = cursor.fetchall() 
    t = Context({'results': rows}) 
    return render_to_response(template_file, t) 

MySQL的CMD:

[[email protected] dc]# mysql dc -e 'SELECT * FROM inventory WHERE hosts="localhost"' 
+----+-----------+-----------+------+ 
| id | groups | hosts  | loc | 
+----+-----------+-----------+------+ 
| 1 | localhost | localhost | sf | 
+----+-----------+-----------+------+ 
+2

爲什麼直接使用MySQL語句而不是ORM? –

+0

伊恩克拉克,我怎麼玩它,因爲這些是大量使用和查詢約10000主機。 –

回答

1

感謝所有爲您及時的幫助..

@eddwinpaz,它得到了固定的看法

= = views.py:

def gethost(request, hostname, template_file="gethost.html"): 
    from django.db import connection, transaction 
    cursor = connection.cursor() 
    cursor.execute("SELECT * FROM inventory WHERE hosts='%s'" % hostname) 
    rows = cursor.fetchall() 
    t = Context({'results': rows}) 
    return render_to_response(template_file, t) 
0

您的網址沒有傳遞任何東西d建議使用ORM而不是基於SQL。

url(r'^gethost/(?P<hostname>[\w\-]+)/$', 'dc.views.gethost'), 
+0

謝謝,在這種情況下,我該如何調用url來形成/構建查詢? –

+0

應該是www.domain.com/gethost/anothersite.com – eddwinpaz

+0

是啊,試過一個,這不會給我輸出讀取分貝... @eddwinpaz,這可能是問題在意見 –

0

看看下面的代碼希望它更清楚你想要達到什麼。確保在你的settings.py文件中有TEMPLATE_DIRS =('var/www/dc/templates /')的URL,在settings.py中使用系統上的路徑。還要確保在INSTALLED_APPS上添加'dc'。

settings.py

TEMPLATE_DIRS =( '無功/網絡/ DC /模板/')

views.py
from django.shortcuts import render, HttpResponseRedirect, render_to_response 
from dc.models import inventory 

def gethost(request, hostname): 

    try: 
     inventory_data = inventory.objets.get(hostname=hostname) 
     return render(request,'gethost.html',{inventory:'inventory_data'}) 

    except inventory.DoesNotExist: 

     return HttpResponseRedirect('/myurl/') 
     # this is a dummy url you must set it to a 404 if you want 

gethost.html
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
</head> 
<body> 
<h2>View Hostname: {{inventory.hostname}}</h2> 

</body> 
</html> 

模型.py

從django.db進口車型

類庫存(models.Model):

hostname = models.CharField(max_length=100) 

def __unicode__(self): 
    return self.hostname