Skip to content

Instantly share code, notes, and snippets.

@h3ct0rjs
Last active December 26, 2016 03:34
Show Gist options
  • Save h3ct0rjs/69664d063db1e0a70cf33f0f4ff0d9bf to your computer and use it in GitHub Desktop.
Save h3ct0rjs/69664d063db1e0a70cf33f0f4ff0d9bf to your computer and use it in GitHub Desktop.
Old cgi, this will show you the number of the last book, easy to understand but difficult if you need at least the same thing in multiple html pages.
<html>
<head><title>Books</title></head>
<body>
<h1>Books</h1>
<ul>
{% for book in book_list %}
<li>{{ book.name }}</li>
{% endfor %}
</ul>
</body>
</html>
# models.py (las tablas de la base de datos)
from django.db import models
class Book(models.Model):
name = models.CharField(maxlength=50)
pub_date = models.DateField()
#!/usr/bin/python
import MySQLdb
print "Content-Type: text/html"
print
print "<html><head><title>Libros</title></head>"
print "<body>"
print "<h1>Los ultimos 10 libros</h1>"
print "<ul>"
conexion = MySQLdb.connect(user='yo', passwd='dejame_entrar', db='mi_base')
cursor = conexion.cursor()
cursor.execute("SELECT nombre FROM libros ORDER BY fecha_pub DESC LIMIT 10")
for fila in cursor.fetchall():
print "<li>%s</li>" % fila[0]
print "</ul>"
print "</body></html>"
conexion.close()
# urls.py (la configuración URL)
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
(r'latest/$', views.latest_books),
)
Todavía no
# views.py (la parte lógica)
from django.shortcuts import render_to_response
from models import Book
def latest_books(request):
book_list = Book.objects.order_by('-pub_date')[:10]
return render_to_response('latest_books.html', {'book_list': book_list})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment