Notes 11/05 on test data, search

Test data

Below is a script to generate test data. I stored it in bookswap/data.py and then you can run it using python data.py from that directory.

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'bookswap.settings'

from main.models import Book
import random

names = ['Alice', 'Bob', 'Carl', 'David', 'Edward', 'Frank']


for w1 in ['The', 'An', 'On']:
    for w2 in ['Psychology', 'Etymology', 'Biology', 'Sociology']:
        for w3 in ['Cats', 'Dogs', 'Computers', 'the Mind']:
            title = '%s %s of %s' % (w1, w2, w3)
            n1 = names[random.randrange(0, len(names))]
            n2 = names[random.randrange(0, len(names))]
            author = n1 + ' ' + n2
            isbn = str(random.random())[2:12]
            b = Book(title=title, author=author, isbn10=isbn, isbn13=isbn,
                description='Essential reading',
                publisher='Wiley', category='Junk')
            b.save()

print Book.objects.all()

Search

We also started to work on a search feature. Here’s the simple view:

def search(request):
    bs = Book.objects.filter(title__icontains=request.GET['search'])
    return HttpResponse("Searching for " + request.GET['search'] + ": " + str(bs))

and you need to link it into the urlconf:

    url(r'^search$', 'main.views.search', name='search'),

and add a search box on the home page:

    <form action='{% url search %}'>
        <input type='text' name='search' value=''>
        <input type='submit' value='Search'>
    </form>