[Answer]-Django + MySQL, form/create mysql query to pass a valid argument to the url

1👍

Thanks all for you timely help..

@eddwinpaz, it got fixed in views

== 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👍

Your url is not passing anything and recomended to use ORM instead of SQL based.

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

0👍

Look at this code below hope it makes more clear of what you want to achieve. make sure on your settings.py there is the URL for the TEMPLATE_DIRS = (‘var/www/dc/templates/’) in your case use the path on your system on settings.py. also make sure on INSTALLED_APPS is ‘dc’ added.

settings.py

TEMPLATE_DIRS = (‘var/www/dc/templates/’)

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>

models.py

from django.db import models

class inventory(models.Model):

hostname = models.CharField(max_length=100)

def __unicode__(self):
    return self.hostname

Leave a comment